20分钟
创建多个 subplot
如果你想创建网格中的许多subplot
,旧式风格的代码非常繁琐:
#旧式风格
fig=plt.figure()
ax1=fig.add_subplot(221)
ax2=fig.add_subplot(222,sharex=ax1,sharey=ax1)
ax3=fig.add_subplot(223,sharex=ax1,sharey=ax1)
ax4=fig.add_subplot(224,sharex=ax1,sharey=ax1)
新式风格的代码直接利用pyplot.subplots()
函数一次性创建:
#新式风格的代码
fig,((ax1,ax2),(ax3,ax4))=plt.subplots(2,2,sharex=True,sharey=True)
ax1.plot(...)
ax2.plot(...)
...
它创建了Figure
和对应所有网格SubPlot
。你也可以不去解包而直接:
#新式风格的代码
fig,((ax1,ax2),(ax3,ax4))=plt.subplots(2,2,sharex=True,sharey=True)
ax1.plot(...)
ax2.plot(...)
...
返回的axs
是一个nrows*ncols
的array
,支持numpy
的索引。
学员评价