Python+Matplotlib绘制多子图的方法详解
作为一种常见的可视化图形操作软件,Matplotlib在日常的生活中应用还是比较广泛的。下面跟着本站小编的视角,带着大家去详细解答Python+Matplotlib绘制多子图的方法。

Matplotlib.pyplot API绘制子图
Matplotlib.pyplot API是Matplotlib常用的绘制和操作API之一。可以通过该API绘制子图,代码如下:
import matplotlib.pyplot as plt
my_dpi=96
plt.figure(figsize=(480/my_dpi,480/my_dpi),dpi=my_dpi)
plt.subplot(221)
plt.plot([1,2,3])
plt.subplot(222)
plt.bar([1,2,3],[4,5,6])
plt.title('plt.subplot(222)')#注意比较和上面面向对象方式的差异
plt.xlabel('set_xlabel')
plt.ylabel('set_ylabel',fontsize=15,color='g')#设置y轴刻度标签
plt.xlim(0,8)#设置x轴刻度范围
plt.xticks(range(0,10,2))#设置x轴刻度间距
plt.tick_params(axis='x',labelsize=20,rotation=45)#x轴标签旋转、字号等
plt.subplot(223)
plt.plot([1,2,3])
plt.subplot(224)
plt.bar([1,2,3],[4,5,6])
plt.suptitle('Matplotlib.pyplot API',color='r')
fig.tight_layout(rect=(0,0,1,0.9))
plt.subplots_adjust(left=0.125,bottom=-0.51,right=1.3,top=0.88,wspace=0.2,hspace=0.2)
#plt.tight_layout()
plt.show()
面向对象方式绘制子图
面向对象方式是Matplotlib最基本的绘图方式之一,可以通过该方式绘制子图,代码如下:
import matplotlib.pyplot as plt
my_dpi=96
fig,axs=plt.subplots(2,2,figsize=(480/my_dpi,480/my_dpi),dpi=my_dpi,sharex=False,sharey=False)
axs[0][0].plot([1,2,3])
axs[0][1].bar([1,2,3],[4,5,6])
axs[0][1].set(title='title')#设置axes及子图标题
axs[0][1].set_xlabel('set_xlabel',fontsize=15,color='g')#设置x轴刻度标签
axs[0][1].set_ylabel('set_ylabel',fontsize=15,color='g')#设置y轴刻度标签
axs[0][1].set_xlim(0,8)#设置x轴刻度范围
axs[0][1].set_xticks(range(0,10,2))#设置x轴刻度间距
axs[0][1].tick_params(axis='x',labelsize=20,rotation=45)#x轴标签旋转、字号等
axs[1][0].plot([1,2,3])
axs[1][1].bar([1,2,3],[4,5,6])
fig.suptitle('Matplotlib object-oriented',color='r')#设置fig即整整张图的标题
plt.subplots_adjust(left=0.125,bottom=-0.61,right=1.3,top=0.88,wspace=0.2,hspace=0.2)
plt.show()
Matplotlib.gridspec.GridSpec绘制子图
Matplotlib.gridspec.GridSpec可以实现更加灵活的子图排版和添加,代码如下:
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
fig=plt.figure(dpi=100,constrained_layout=True)
gs=GridSpec(3,3,figure=fig)
ax1=fig.add_subplot(gs[0,0:1])
plt.plot([1,2,3])
ax2=fig.add_subplot(gs[0,1:3])
#ax3=fig.add_subplot(gs[1,0:
原创文章,作者:小编小本本,如若转载,请注明出处:https://www.benjiyun.com/yunzhujiyunwei/vps-yunwei/7195.html
