0%

matplotlib入门

折线图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import matplotlib.pyplot as plt
import numpy as np
x=np.linspace(-5,5,100)
y1=2*x+4
y2=x**2

plt.figure()


#加标题 plt.suptitle
plt.suptitle('figure1')

#设定x,y轴名称 plt.xlable,plt.ylabel
plt.xlabel('x')
plt.ylabel('y')

#设定x,y轴的范围 plt.xlim,plt.ylim
# plt.xlim((-5,5))
# plt.ylim((-10,10))

#设置坐标轴的单位距离和单元名称
# plt.xticks(np.linspace(-5,5,11))
# plt.yticks(np.linspace(-5,25,31))
# plt.yticks([-10,-5,0,5,12],[r'$very\ bad$',r'$bad\ \alpha$',r'$ok$',r'$good$',r'$very\ good$'])

#设置轴的位置
'''
1.获得当前四边轴线(get current axis)plt.gca()
2.去掉右边和上边的轴线 ax.spines['right and top'].set_color('none')
3.令x为下边轴线, ax.xaxis.set_ticks_positions('bottom')
令y为左边轴线, ax.yaxis.set_ticks_positions('left')
4.设置原点坐标((0,0)为原点)
ax.spines['bottom'].set_position(('data',0))
ax.spines['left'].set_position(('data',0))
'''
ax=plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
ax.spines['bottom'].set_position(('data',0))
ax.spines['left'].set_position(('data',0))
# ax.derection
# ax.spines['bottom'].set_axisline_style("-|>")
# ax.spines['bottom'].set_axisline_style("-|>")

#控制线条的颜色,宽度,和linestyle[solid,dotted,dashed,dashdot]
l2,=plt.plot(x,y2)
l1,=plt.plot(x,y1,linestyle='solid',linewidth=1.0,color='green',)

#设置图例 plt.legend()
#无参数 已在plt.plot(label='y1')中加入label参数
plt.legend(handles=[l1,l2],labels=['y1','y2'],loc='best')

#加注解 annotation,比如给线的交点加注解
#标出 y1=2*x+4 和 y2=x**2 的交点
#利用零点定理找“近似”交点,(近似由于线条是由拟合的,真正的零点不一定生成了)
idx = np.argwhere(np.diff(np.sign(y1-y2))).flatten()
plt.plot(x[idx], y2[idx], 'ro',color='red')

for i in range(len(idx)):
plt.plot([x[idx][i],x[idx][i]],[y2[idx][i],0],'k--',lw=2.5)

#加annotation
plt.annotate(r'(%s,%s)'%(round(x[idx][1],1),round(y2[idx][1],1)),xy=(x[idx][1],y2[idx][1]),xycoords='data',
xytext=(+4,+3),fontsize=10,
arrowprops=dict(arrowstyle='->',connectionstyle='arc3,rad=0.2'))

#加一些说明
plt.text(-4,5,r'$this\ is\ some\ text\ \sigma_i\ \alpha$')


#ticks能见度
for label in ax.get_xticklabels()+ax.get_yticklabels():
label.set_fontsize(12)
label.set_bbox(dict(facecolor='pink',edgecolor='None',alpha=0.7))


plt.show()

散点图

1
2
3
4
5
6
7
8
9
10
11
12
n=1024
X=np.random.normal(0,1,n)
Y=np.random.normal(0,1,n)
T=np.arctan2(Y,X) # for color value
plt.scatter(X,Y,s=75,c=T,alpha=0.7)
plt.xlim(-1.5,1.5)
plt.ylim(-1.5,1.5)
plt.xticks(())
plt.yticks(())

plt.figure()
plt.scatter(np.linspace(-1,1,20),np.linspace(-1,1,20))

等高线

1
2
3
4
5
6
7
8
9
10
def f(x,y):
return (1-x/2+x**5+y**3)*np.exp(-x**2-y**2)
n=256
x=np.linspace(-3,3,n)
y=np.linspace(-3,3,n)
X,Y=np.meshgrid(x,y)
plt.contourf(X,Y,f(X,Y),8,alpha=0.75,cmap=plt.cm.hot)
C = plt.contour(X,Y,f(X,Y),8,colors='black')
plt.clabel(C,inline=True,fontsize=10)
plt.show()

柱状图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import matplotlib.pyplot as plt
import numpy as np
#plt.bar 柱状图
n=12
X=np.arange(n)
Y1=np.random.uniform(0,1.0,n)
Y2=np.random.uniform(0.5,1.0,n)*(1-X/float(n))

ax=plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
ax.spines['bottom'].set_position(('data',0))
ax.spines['left'].set_position(('data',-0.50))

plt.xlim((-1,12))
plt.ylim((-1,1))

plt.bar(X,+Y1,facecolor='#9999fF',edgecolor='white')
plt.bar(X,-Y2,facecolor='#ff9999',edgecolor='white')

for x,y in zip(X,Y1):
plt.text(x+0.04,y+0.05,'%0.2f'%y,ha='center',va='bottom')

for x,y in zip(X,Y2):
plt.text(x+0.04,-y-0.05,'%0.2f'%-y,ha='center',va='top')
plt.show()

3D图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
fig=plt.figure()
ax=Axes3D(fig)
X=np.arange(-4,4,0.25)
Y=np.arange(-4,4,0.25)
X,Y = np.meshgrid(X,Y)
R=np.sqrt(X**2+Y**2)
Z=np.sin(R)

ax.plot_surface(X,Y,Z,rstride=1,cstride=1,cmap=plt.get_cmap('rainbow'))
ax.contourf(X,Y,Z,zdir='z',offset=-2,cmap='rainbow')
ax.set_zlim(-2,2)

多子图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
##method1:
plt.figure()
plt.subplot(2,2,1)
plt.plot([0,1],[0,1])
plt.subplot(2,2,2)
plt.plot([0,1],[0,1])
plt.subplot(2,2,3)
plt.plot([0,1],[0,1])
plt.subplot(2,2,4)
plt.plot([0,1],[0,1])
plt.show()

##method2:
plt.figure()
plt.subplot(2,1,1)
plt.plot([0,1],[0,1])
plt.subplot(2,3,4)
plt.plot([0,1],[0,2])
plt.subplot(2,3,5)
plt.plot([0,1],[0,3])
plt.subplot(2,3,6)
plt.plot([0,1],[0,4])
plt.show()

##method3:
plt.figure()
ax1 = plt.subplot2grid((3,3),(0,0),colspan=3,rowspan=1)
ax1.plot([1,2],[1,2])
ax1.set_title('ax1_title')

ax2 = plt.subplot2grid((3,3),(1,0),colspan=2,rowspan=1)
ax2.plot([1,2],[1,2])
ax2.set_title('ax2_title')

ax3 = plt.subplot2grid((3,3),(1,2),colspan=1,rowspan=2)
ax3.plot([1,2],[1,2])
ax3.set_title('ax3_title')

ax4 = plt.subplot2grid((3,3),(2,0),colspan=1,rowspan=1)
ax4.plot([1,2],[1,2])
ax4.set_title('ax3_title')

ax5 = plt.subplot2grid((3,3),(2,1),colspan=1,rowspan=1)
ax5.plot([1,2],[1,2])
ax5.set_title('ax5_title')
plt.show()

##method4:
plt.figure()
gs = gridspec.GridSpec(3,3)
ax1 = plt.subplot(gs[0,:])
ax2 = plt.subplot(gs[1,:2])
ax3 = plt.subplot(gs[1:3,2])
ax4 = plt.subplot(gs[2,:1])
ax5 = plt.subplot(gs[2,1:2])
plt.show()

##method5:
f,((ax11,ax12),(ax21,ax22)) = plt.subplots(2,2,sharex=True,sharey=True)
ax11.plot([1,2],[2,3])

多子图1

多子图2

图中图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
fig = plt.figure()
x = np.arange(1,8,1)
y = [1,3,4,2,5,8,6]
left,bottom,width,height =0.1,0.1,0.8,0.8
ax1 = fig.add_axes([left,bottom,width,height])
ax1.plot(x,y,'r')
ax1.set_xlabel('x')
ax1.set_ylabel('y')
ax1.set_title('x')

left,bottom,width,height =0.2,0.5,0.25,0.25
ax2 = fig.add_axes([left,bottom,width,height])
ax2.plot(y,x,'b')
ax2.set_xlabel('x')
ax2.set_ylabel('y')
ax2.set_title('title inside 1')

plt.axes([0.6,0.2,0.25,0.25])
plt.plot(y[::-1],x,'g')
plt.xlabel('x')
plt.ylabel('y')
plt.title('title inside 2')

plt.show()

参考资料:
https://morvanzhou.github.io/tutorials/data-manipulation/plt/

https://matplotlib.org/gallery/index.html

https://www.bilibili.com/video/av16378354?from=search&seid=11592256393211605806