Pyplot common drawing method

Introduction: Pyplot is in python matplotlib a powerful drawing tool, which is inside a simple function-oriented style API, to cope with routine work among the simple drawing work, in fact, can not say it plotted relatively simple, it can cope many complex charts, which of course no other object-oriented API so personal, but can also cope with most of the work, the next chart is drawn with Pyplot Fig. just recently doing learning machine learning, to model the assessment will be used drawing, here compiled a number of common usage;
Here Insert Picture Description

Prepare data

# 导入必要的包
import numpy as np
import matplotlib.pyplot as plt

# 在0到2这个区间内均匀找出100个数
x = np.linspace(0.,2.,100)
# x 中的每个元素取sin
y = np.sin(x*np.pi)
# 从标准正态分布中随机取100个数
y1 = np.random.randn(100)

Use plot () - A line in FIG.

# 参数含义 x,y 分别为两轴的数据,ls:代表图中线的格式 c:线的颜色 lw:线宽度,label: 线的标签
plt.plot(x,y,ls="--",c='r',lw=2,label="test_line1")
# 显示图
plt.show()

Here Insert Picture Description
Line style:

character description
‘-’ The solid line style
‘–’ Dash style
‘-.’ Dotted line style
‘:’ Dash pattern
‘.’ Point mark
‘,’ Pixel tags
'The' Round mark
'V' Inverted triangle mark
‘^’ Triangle mark
‘<’ Left triangular mark
‘>’ Right triangle mark
‘1’ Down arrow
‘2’ Arrow mark
‘3’ Left arrow
‘4’ Right arrow
‘s’ Square mark
‘p’ Pentagonal mark
‘*’ Star mark
‘h’ Hexagon mark 1
‘H’ Hexagon mark 2
‘+’ Plus sign
‘x’ X marks
‘D’ Rhombus
‘d’ Narrow rhombus
‘|’ A vertical line marking
‘_’ Horizontal line marks

The following is an abbreviation of color:

character colour
‘b’ blue
‘g’ green
‘r’ red
‘c’ Blue color
‘m’ Magenta
'Y' yellow
‘k’ black
‘w’ white

scatter () is used - Scatter

# 参数跟上类似
plt.scatter(x,y1,c="b",label="test_scatter1")

Here Insert Picture Description

xlabel (), ylabel () xy axis disposed tab

# x轴的标签
plt.xlabel(xlabel="x-axis")
# y轴的标签
plt.ylabel(ylabel="y-axis")

Here Insert Picture Description

grid () - grid lines

# linestyle:设置网格线的格式,':'虚线,'-'实线  color:网格线的颜色 linewidth:线条宽度
# 参数也可以用缩写 ls,c,lw , …
plt.grid(linestyle=":",color="r",linewidth=1)

Here Insert Picture Description

axvline (), axhline () - Set vertical and horizontal reference line

# 设置垂直参考线
plt.axvline(x=0.5,ls="--",lw=1,c='b')
# 设置水平参考线
plt.axhline(y=0.5,ls="--",lw=1,c='r')

Here Insert Picture Description

axvapan (), axhspan () - Set vertical and horizontal reference region

plt.plot(x,y,ls=":",c='r',lw=1,label="test_line1")

# 设置垂直方向参考区域 xmin与xmax设置x轴方向的跨度,facecolor:填充的颜色, alpha:透明度 0~1
plt.axvspan(xmin=0.4,xmax=0.6,facecolor="r",alpha=0.1)
# 设置水平防线参考区域 参数参考垂直方向的解释
plt.axhspan(ymin=0.3,ymax=0.6,facecolor="b",alpha=0.1)

Here Insert Picture Description

annotate () - with directivity annotated

plt.plot(x,y,ls=":",c='r',lw=1,label="test_line1")
# 参数含义:
# s: 注释的文本
# xy:需要注释图中的哪个坐标
# xytext:文本显示在图中的位置
# weight:文字的样式,这里是加粗
# color:文字的颜色
# arrowprops箭头的样式,以一个词典方式传入参数
plt.annotate(s="max",
             xy=(0.5,1.0),
             xytext=(0.75,0.8),
             weight="bold",
             color="b",
             arrowprops={"arrowstyle":"->","connectionstyle":"arc3","color":"b"})

Here Insert Picture Description

text () - non-directional Comment

plt.plot(x,y,ls=":",c='r',lw=1,label="test_line1")
# 参数意义类似 x,y 表示注释文本在图像中的位置
plt.text(s="y=sin(x)",x=1.0,y=0.0,weight="bold",color="b")

Here Insert Picture Description

title () - add title

plt.title("This is title")

Here Insert Picture Description

legend () - Add a legend

plt.plot(x,y,ls=":",c='r',lw=1,label="test_line1")

# 显示图例 upper:上 lower:下 center:居中 right:右 left:左 空格隔开进行组合
plt.legend(loc="lower left")

Here Insert Picture Description

bar () - Histogram

# 准备数据
x = np.arange(0,9)
y = np.random.randint(0,10,9)
# x 轴上的标签
labels = [chr(i+65) for i in range(9)]
# align:对齐方式,color:颜色 tick_label:x属性的标签 hatch:柱上的遮盖样式
plt.bar(x,y,align="center",color="c",tick_label=labels,hatch="/")

Here Insert Picture Description

barh () - bar

# 参数格式和柱状图一样
plt.barh(x,y,align="center",color="c",tick_label=labels,hatch="/")

Here Insert Picture Description

hist () - Histogram

x = np.random.randint(1,9,100)
bins = np.arange(1,10,1)

# x:数据,bins:x轴上所有的分支,histtype:直方图的类型
plt.hist(x,bins=bins,histtype="bar",color="g",rwidth=1,alpha=0.6)

Here Insert Picture Description

pie () - Pie Chart

labels = [chr(i+65) for i in range(6)]
soldNums = np.random.randint(1,100,6)
# 各个部分的颜色
colors = ["r","g","b"]*2
# autopct:显示百分比的格式
plt.pie(soldNums,colors=colors,labels=labels,startangle=60,autopct="%3.1f%%")

Here Insert Picture Description

polar () - polar FIG.

# 每个数据所在度数位置 弧度制
theta = np.linspace(0,2*np.pi,12,endpoint=False)
# 每个位置的值大小
data = 50 * np.random.random(12)

# c:折线颜色,marker:顶点样式,lw:折线宽度,mfc:顶点颜色,ms:顶点大小
plt.polar(theta,data,c="#FFAAFF",lw=2,marker="o",mfc="b",ms=5)

Here Insert Picture Description

scatter () - Bubble FIG.

x = np.random.rand(100)
y = np.random.rand(100)
c = np.random.rand(100)
#s:气泡的大小,marker:气泡样式,cmap:要将浮点数映射的颜色表 
plt.scatter(x,y,s=np.power(x*10+5*y,3),c=c,marker="o",cmap=mpl.cm.RdYlBu)

Here Insert Picture Description

stem () - swab FIG.

x = np.linspace(0,7,20)
y = np.random.randn(20)

# linefmt:竖直方向线条格式
# markerfmt:顶点的格式
# basefmt:水平方向线条格式
plt.stem(x,y,linefmt="--",markerfmt="o",basefmt="-")

Here Insert Picture Description

boxplot () - boxplot

x = np.random.randn(1000)
plt.boxplot(x)
plt.grid(axis="y",ls=":",color="gray",alpha=0.3)

Here Insert Picture Description

errorbar () - error bars in FIG.

x = np.linspace(0.1,0.6,6)
y = np.exp(x)

# fmt:样式
# yerr:y轴方向的误差计算方法
# xerr:x轴方向的误差计算方法
plt.errorbar(x,y,fmt="ro:",yerr=0.1,xerr=0.02)
# 限制x轴的上下限
plt.xlim(0,0.7)

Here Insert Picture Description

The complete code

from matplotlib import cm as cm
x = np.linspace(0.5,3.5,100)
y = np.sin(x)
y1= np.random.randn(100)
plt.scatter(x,y1,c="0.25",label="scatter figure")
plt.plot(x,y,ls="--",lw=2,label="plot figure")
for spine in plt.gca().spines.keys():
    if spine == "top" or spine == "right":
        plt.gca().spines[spine].set_color("none")
plt.gca().xaxis.set_ticks_position("bottom")
plt.gca().yaxis.set_ticks_position("left")
plt.xlim(0.0,4.0)
plt.ylim(-3.0,3.0)
plt.ylabel("y_axis")
plt.xlabel("x_axis")
plt.grid(True,ls=":",color="r")
plt.axhline(y=0.0,c="r",ls="--",lw=2)
plt.axvspan(xmin=1.0,xmax=2.0,facecolor="y",alpha=0.3)

plt.annotate("maximum",xy=(np.pi/2,1.0),
            xytext=((np.pi/2)+0.15,1.5),weight="bold",color="r",
            arrowprops={"arrowstyle":"->","connectionstyle":"arc3","color":"b"})


plt.annotate("spines",xy=(0.75,-3),
            xytext=(0.35,-2.25),weight="bold",color="b",
            arrowprops={"arrowstyle":"->","connectionstyle":"arc3","color":"b"})

plt.annotate("",xy=(0,-2.78),
            xytext=(0.4,-2.32),
            arrowprops={"arrowstyle":"->","connectionstyle":"arc3","color":"b"})

plt.annotate("",xy=(3.5,-2.98),
            xytext=(3.6,-2.70),
            arrowprops={"arrowstyle":"->","connectionstyle":"arc3","color":"b"})


plt.text(3.6,-2.70,"'|' is tickline",weight="bold",color="b")
plt.text(3.6,-2.95,"3.5 is ticklabel",weight="bold",color="b")

plt.title("pyplot show test")
plt.legend()
Published 27 original articles · won praise 62 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_42359956/article/details/105389080