matplotlib 在子区网格中重新定位子区

6kkfgxo0  于 2023-03-19  发布在  其他
关注(0)|答案(2)|浏览(146)

我正在尝试绘制一个包含7个子图的图。目前我正在绘制两列,一列包含4个图,另一列包含3个图,即:

我以如下方式构建这一情节:

  1. #! /usr/bin/env python
  2. import numpy as plotting
  3. import matplotlib
  4. from pylab import *
  5. x = np.random.rand(20)
  6. y = np.random.rand(20)
  7. fig = figure(figsize=(6.5,12))
  8. subplots_adjust(wspace=0.2,hspace=0.2)
  9. iplot = 420
  10. for i in range(7):
  11. iplot += 1
  12. ax = fig.add_subplot(iplot)
  13. ax.plot(x,y,'ko')
  14. ax.set_xlabel("x")
  15. ax.set_ylabel("y")
  16. savefig("subplots_example.png",bbox_inches='tight')

然而,对于出版物来说,我认为这看起来有点难看--我想做的是将最后一个子情节移到两列之间的中心。那么,调整最后一个子情节的位置使其居中的最佳方法是什么呢?也就是说,将前6个子情节放在3X 2的网格中,将下面的最后一个子情节放在两列之间居中。如果可能的话,我希望能够保留for循环,这样我就可以简单地用途:

  1. if i == 6:
  2. # do something to reposition/centre this plot
mwg9r5ms

mwg9r5ms1#

使用网格规格(doc)和4x4网格,并使每个图跨越2列,如下所示:

  1. import matplotlib.gridspec as gridspec
  2. gs = gridspec.GridSpec(4, 4)
  3. ax1 = plt.subplot(gs[0, 0:2])
  4. ax2 = plt.subplot(gs[0,2:])
  5. ax3 = plt.subplot(gs[1,0:2])
  6. ax4 = plt.subplot(gs[1,2:])
  7. ax5 = plt.subplot(gs[2,0:2])
  8. ax6 = plt.subplot(gs[2,2:])
  9. ax7 = plt.subplot(gs[3,1:3])
  10. fig = gcf()
  11. gs.tight_layout(fig)
  12. ax_lst = [ax1,ax2,ax3,ax4,ax5,ax6,ax7]
oknrviil

oknrviil2#

如果你想保留for循环,你可以用subplot2grid来安排你的绘图,它允许一个colspan参数:

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. x = np.random.rand(20)
  4. y = np.random.rand(20)
  5. fig = plt.figure(figsize=(6.5,12))
  6. plt.subplots_adjust(wspace=0.2,hspace=0.2)
  7. iplot = 420
  8. for i in range(7):
  9. iplot += 1
  10. if i == 6:
  11. ax = plt.subplot2grid((4,8), (i//2, 2), colspan=4)
  12. else:
  13. # You can be fancy and use subplot2grid for each plot, which doesn't
  14. # require keeping the iplot variable:
  15. # ax = plt.subplot2grid((4,2), (i//2,i%2))
  16. # Or you can keep using add_subplot, which may be simpler:
  17. ax = fig.add_subplot(iplot)
  18. ax.plot(x,y,'ko')
  19. ax.set_xlabel("x")
  20. ax.set_ylabel("y")
  21. plt.savefig("subplots_example.png",bbox_inches='tight')

展开查看全部

相关问题