python pyplot:如何组织布局?
在查看matplotlib的文档时,我发现了一个例子:
http://matplotlib.org/users/tight_layout_guide.html
import matplotlib.pyplot as plt
def example_plot(ax,pid, fontsize=12):
ax.plot([1, 2])
ax.locator_params(nbins=3)
ax.set_xlabel('x-label', fontsize=fontsize)
ax.set_ylabel('y-label', fontsize=fontsize)
ax.set_title('Title'+str(pid), fontsize=fontsize)
plt.close('all')
fig = plt.figure()
ax1 = plt.subplot(221)
ax2 = plt.subplot(223)
ax4 = plt.subplot(122)
example_plot(ax1,1)
example_plot(ax2,2)
example_plot(ax4,4)
plt.tight_layout()
plt.show()
这个例子生成了一个两列的布局,左边是一列有两行,右边是一列有一行。 这似乎和subplot的API说明一致: http://matplotlib.org/api/pyplot_api.html
subplot(211)会在一个图形中生成一个子图,表示在一个2行1列的假想网格中的顶部图(也就是第一个图)。虽然实际上并没有这个网格,但从概念上讲,这就是返回的子图被放置的位置。
我现在想在左边的列中再加一行(总共3行)。根据我的理解,应该这样做:
import matplotlib.pyplot as plt
def example_plot(ax,pid, fontsize=12):
ax.plot([1, 2])
ax.locator_params(nbins=3)
ax.set_xlabel('x-label', fontsize=fontsize)
ax.set_ylabel('y-label', fontsize=fontsize)
ax.set_title('Title'+str(pid), fontsize=fontsize)
plt.close('all')
fig = plt.figure()
ax1 = plt.subplot(321) # changed "2" by "3"
ax2 = plt.subplot(323) # changed "2" by "3"
ax3 = plt.subplot(324) # line added
ax4 = plt.subplot(122)
example_plot(ax1,1)
example_plot(ax2,2)
example_plot(ax3,3) # line added
example_plot(ax4,4)
plt.tight_layout()
plt.show()
但我觉得我可能哪里做错了,因为这样显示的布局是对的,但第一列的第三个图却没有显示出来……
1 个回答
2
当你创建一个3行2列的子图网格时,左边那一列的图会被编号为1、3和5。如果你把这一行改成ax3 = plt.subplot(325)
,就应该能正常工作了。