Matplotlib再来一次 文章目录 一、基础用法 二、figure图像 三、设置坐标轴 四、legend图例 五、标注 六、散点图 七、直方图
Matplotlib再来一次
文章目录
- 一、基础用法
- 二、figure图像
- 三、设置坐标轴
- 四、legend图例
- 五、标注
- 六、散点图
- 七、直方图
- 八、等高线图
- 九、3D图
- 十、subplot
- 十一、动态图
配合
机器学习食用更佳。
一、基础用法
- 画直线
import numpy as np
%matplotlib inlinex = np.linspace(-1,1,100)#从-1到1生成100个点
y = 2*x + 1
plt.plot(x,y)
plt.show()
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-6gU2Ghlu-1641824116961)(output_2_0.png)] Python进阶—Matplotlib_开发语言](http://img.558idc.com/uploadfile/allimg/python/01104654_62be601e9c9592930.png)
二、figure图像
- 不同图像在不同的figure中
- 改变图像大小
- plt.plot(x,y2,color=‘blue’,linewidth=5.0,linestyle=’-’)
y1 = 2*x+1
y2 = x ** 2
plt.figure()
plt.plot(x,y1)
plt.figure(figsize=(8,5)) # 改变图像大小
plt.plot(x,y2)
plt.show()
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-UEoRYrsr-1641824116963)(output_4_0.png)] Python进阶—Matplotlib_python_02](http://img.558idc.com/uploadfile/allimg/python/01104654_62be601ec75d223440.png)
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-LtDf75Fc-1641824116963)(output_4_1.png)] Python进阶—Matplotlib_Matplotlib_03](http://img.558idc.com/uploadfile/allimg/python/01104655_62be601f1ebeb94005.png)
y1 = 2 *x + 1
y2 = x ** 2
plt.plot(x,y1,color='red',linewidth=1.0,linestyle='--')
plt.plot(x,y2,color='blue',linewidth=5.0,linestyle='-')[<matplotlib.lines.Line2D at 0x7fc5d44dd6a0>]
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-xC39A98a-1641824116964)(output_5_1.png)] Python进阶—Matplotlib_计算机视觉_04](http://img.558idc.com/uploadfile/allimg/python/01104655_62be601f4f99746747.png)
三、设置坐标轴
- xlim、ylim限制范围
- xlabel、ylabel描述
- xticks、yticks 修改坐标范围或者类型
- 画坐标图
y1 = 2 *x + 1
y2 = x ** 2
# xy范围
plt.xlim((-1,2))
plt.ylim((-2,3))
# xy描述
plt.xlabel('I AM X')
plt.ylabel('I AM Y')
plt.plot(x,y1,color='red',linewidth=1.0,linestyle='--')
plt.plot(x,y2,color='blue',linewidth=5.0,linestyle='-')[<matplotlib.lines.Line2D at 0x7fc5d4727470>]
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-0AM63W2p-1641824116965)(output_7_1.png)] Python进阶—Matplotlib_python_05](http://img.558idc.com/uploadfile/allimg/python/01104655_62be601f9354465604.png)
print(new_ticks)[-2. -1.6 -1.2 -0.8 -0.4 0. 0.4 0.8 1.2 1.6 2. ]x = np.linspace(-3,3,100)
y1 = 2 *x + 1
y2 = x ** 2
# xy范围
plt.xlim((-1,2))
plt.ylim((-2,3))
# xy描述
plt.xlabel('I AM X')
plt.ylabel('I AM Y')
plt.xticks(new_ticks)
plt.yticks([-2,-1,0,1,2,3],['level0','level1','level2','level3','level4','level5'])
plt.plot(x,y1,color='red',linewidth=1.0,linestyle='--')
plt.plot(x,y2,color='blue',linewidth=5.0,linestyle='-')[<matplotlib.lines.Line2D at 0x7fc5d60c52e8>]
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-XdJ8KjZM-1641824116966)(output_9_1.png)] Python进阶—Matplotlib_Matplotlib_06](http://img.558idc.com/uploadfile/allimg/python/01104655_62be601fc5fb782363.png)
y1 = 2*x + 1
y2 = x**2
#xy范围
plt.xlim((-1,2))
plt.ylim((-2,3))
#xy描述
plt.xlabel('I AM X')
plt.ylabel('I AM Y')
plt.plot(x,y1,color='red',linewidth=1.0,linestyle='--')
plt.plot(x,y2,color='blue',linewidth=5.0,linestyle='-')
new_ticks = np.linspace(-2,2,11)
print(new_ticks)
plt.xticks(new_ticks)
plt.yticks([-1,0,1,2,3],
['level1','level2','level3','level4','level5'])
# 得到当前的坐标
ax = plt.gca()
ax.spines['right'].set_color('red') # 把右边颜色变成红色
ax.spines['top'].set_color('none') # 把上边去掉
# 把x轴的刻度设置为‘bottom’
# 把y轴的刻度设置为‘left’
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
# 设置bottom对应到0点
# 设置left对应到0点
ax.spines['bottom'].set_position(('data',0))
ax.spines['left'].set_position(('data',0))
plt.show()[-2. -1.6 -1.2 -0.8 -0.4 0. 0.4 0.8 1.2 1.6 2. ]
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-XM5oNfZk-1641824116967)(output_10_1.png)] Python进阶—Matplotlib_3d_07](http://img.558idc.com/uploadfile/allimg/python/01104656_62be602004af199738.png)
四、legend图例
legend
l1, = plt.plot(x,y1,color=‘red’,linewidth=1.0,linestyle=’–’)
l2, = plt.plot(x,y2,color=‘blue’,linewidth=5.0,linestyle=’-’)
plt.legend(handles=[l1,l2],labels=[‘test1’,‘test2’],loc=‘best’) # loc是图例位置 loc:best是自动选择最佳位置
x = np.linspace(-3,3,100)y1 = 2*x + 1
y2 = x**2
#xy范围
plt.xlim((-1,2))
plt.ylim((-2,3))
#xy描述
plt.xlabel('I AM X')
plt.ylabel('I AM Y')
l1, = plt.plot(x,y1,color='red',linewidth=1.0,linestyle='--')
l2, = plt.plot(x,y2,color='blue',linewidth=5.0,linestyle='-')
plt.legend(handles=[l1,l2],labels=['test1','test2'],loc='best') # loc是图例位置 loc:best是自动选择最佳位置
new_ticks = np.linspace(-2,2,11)
print(new_ticks)
plt.xticks(new_ticks)
plt.yticks([-1,0,1,2,3],
['level1','level2','level3','level4','level5'])
plt.show()[-2. -1.6 -1.2 -0.8 -0.4 0. 0.4 0.8 1.2 1.6 2. ]
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-dopfAOBm-1641824116967)(output_12_1.png)] Python进阶—Matplotlib_开发语言_08](http://img.558idc.com/uploadfile/allimg/python/01104656_62be602034cc913487.png)
五、标注
x = np.linspace(-1,1,100)y1 = 2*x + 1
plt.plot(x,y1,color='red',linewidth=1.0,linestyle='-')
#gca get current axis
ax = plt.gca()
#把右边和上边的边框去掉
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
#把x轴的刻度设置为‘bottom’
#把y轴的刻度设置为‘left’
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
#设置bottom对应到0点
#设置left对应到0点
ax.spines['bottom'].set_position(('data',0))
ax.spines['left'].set_position(('data',0))
x0 = 0.5
y0 = 2*x0 + 1
#画点
plt.scatter(x0,y0,s=50,color='b')
#画虚线
plt.plot([x0,x0],[y0,0],'k--',lw=2)
plt.annotate(r'$2x+1=%s$' % y0,xy=(x0,y0),xytext=(+30,-30),textcoords='offset points',fontsize=16,
arrowprops=dict(arrowstyle='->',connectionstyle='arc3,rad=.2'))
plt.text(-1,2,r'$this\ is\ the\ text$',fontdict={'size':'16','color':'r'})
plt.show()
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-XK2W3Kpk-1641824116968)(output_14_0.png)] Python进阶—Matplotlib_3d_09](http://img.558idc.com/uploadfile/allimg/python/01104656_62be60208ba142789.png)
六、散点图
plt.scatter(x,y,s=50,c=‘b’,alpha=0.5) # alpha透明度
plt.scatter(np.arange(5),np.arange(5))plt.show()
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-cyvI2beC-1641824116969)(output_16_0.png)] Python进阶—Matplotlib_3d_10](http://img.558idc.com/uploadfile/allimg/python/01104656_62be6020d13e683539.png)
y = np.random.normal(0,1,500)
plt.scatter(x,y,s=50,c='b',alpha=0.5) # alpha透明度
plt.xlim((-2,2))
plt.ylim((-2,2))
plt.xticks(())
plt.yticks(())
plt.show()
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-piusUuUc-1641824116969)(output_17_0.png)] Python进阶—Matplotlib_3d_11](http://img.558idc.com/uploadfile/allimg/python/01104657_62be60211ae5c68942.png)
七、直方图
- plt.bar(x,y,facecolor=’#9999ff’,edgecolor=‘white’) # edgecolor 边框颜色
y = 2**x + 10
plt.bar(x,y)
plt.show()
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-MNaaMdO7-1641824116970)(output_19_0.png)] Python进阶—Matplotlib_Matplotlib_12](http://img.558idc.com/uploadfile/allimg/python/01104657_62be60215d5e51443.png)
y = 2**x + 10
plt.bar(x,-y)
plt.show()
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-24oKfQ3v-1641824116970)(output_20_0.png)] Python进阶—Matplotlib_3d_13](http://img.558idc.com/uploadfile/allimg/python/01104657_62be6021a0cef21226.png)
y = 2**x + 10
plt.bar(x,y,facecolor='#9999ff',edgecolor='white') # edgecolor 边框颜色
plt.show()
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-KGrKOxUl-1641824116971)(output_21_0.png)] Python进阶—Matplotlib_开发语言_14](http://img.558idc.com/uploadfile/allimg/python/01104657_62be6021d3dff18126.png)
y = 2**x + 10
plt.bar(x,y,facecolor='#9999ff',edgecolor='white')
for x,y in zip(x,y):
plt.text(x,y,'%.2f' % y,ha='center',va='bottom')
plt.show()
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-mmMcdAv3-1641824116971)(output_22_0.png)] Python进阶—Matplotlib_计算机视觉_15](http://img.558idc.com/uploadfile/allimg/python/01104658_62be60222112d30633.png)
八、等高线图
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’,linewidths=.5)
plt.clabel(C,inline=True,fontsize=10)
return (1-x/2+x**5+y**3)*np.exp(-x**2-y**2)
x = np.linspace(-3,3,100)
y = np.linspace(-3,3,100)
X,Y = np.meshgrid(x,y)
plt.contourf(X,Y,f(X,Y),8,alpha=0.75,cmap=plt.cm.hot)
plt.xticks(())
plt.yticks(())
plt.show()
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-uLaj5y8G-1641824116972)(output_24_0.png)] Python进阶—Matplotlib_计算机视觉_16](http://img.558idc.com/uploadfile/allimg/python/01104658_62be6022749f380911.png)
return (1-x/2+x**5+y**3)*np.exp(-x**2-y**2)
x = np.linspace(-3,3,100)
y = np.linspace(-3,3,100)
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',linewidths=.5)
plt.clabel(C,inline=True,fontsize=10)
plt.xticks(())
plt.yticks(())
plt.show()
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-d4mYI9Ry-1641824116972)(output_25_0.png)] Python进阶—Matplotlib_计算机视觉_17](http://img.558idc.com/uploadfile/allimg/python/01104658_62be6022dacff43817.png)
九、3D图
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)
import numpy as np
from mpl_toolkits.mplot3d import Axes3Dfig = 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'))
plt.show()
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-RI3t1RbJ-1641824116973)(output_28_0.png)] Python进阶—Matplotlib_计算机视觉_18](http://img.558idc.com/uploadfile/allimg/python/01104659_62be60234a17847972.png)
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)
plt.show()
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-jWalGpef-1641824116973)(output_29_0.png)] Python进阶—Matplotlib_计算机视觉_19](http://img.558idc.com/uploadfile/allimg/python/01104659_62be6023b4a9a35777.png)
十、subplot
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(223)
plt.plot([0,1],[0,1])
plt.subplot(224)
plt.plot([0,1],[0,1])
plt.show()
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-L1yQoiuA-1641824116974)(output_31_0.png)] Python进阶—Matplotlib_Matplotlib_20](http://img.558idc.com/uploadfile/allimg/python/01104700_62be60245494c51128.png)
plt.subplot(2,1,1)
plt.plot([0,1],[0,1])
plt.subplot(2,3,4)
plt.plot([0,1],[0,1])
plt.subplot(235)
plt.plot([0,1],[0,1])
plt.subplot(236)
plt.plot([0,1],[0,1])
plt.show()
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-5URht8AW-1641824116974)(output_32_0.png)] Python进阶—Matplotlib_计算机视觉_21](http://img.558idc.com/uploadfile/allimg/python/01104700_62be6024b4d0b84795.png)
十一、动态图
import matplotlib.pyplot as pltimport numpy as np
from matplotlib import animationfig,ax = plt.subplots()
x = np.arange(0,2*np.pi,0.01)
line, = ax.plot(x,np.sin(x))
def animate(i):
line.set_ydata(np.sin(x+i/10))
return line,
def init():
line.set_ydata(np.sin(x))
return line,
ani = animation.FuncAnimation(fig=fig,func=animate,init_func=init,interval=20)
plt.show()
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-RruO0gap-1641824116974)(output_35_0.png)] Python进阶—Matplotlib_计算机视觉_22](http://img.558idc.com/uploadfile/allimg/python/01104701_62be60252860b45568.png)
