matplotlib Gridspec跨越分数列宽

ncecgwcz  于 2023-10-24  发布在  其他
关注(0)|答案(2)|浏览(102)

我想要一个在第一行有两个子图的图,每个子图跨越1.5列,在第二行有三个图,每个子图一列宽。matplotlib和gridspec可以做到这一点吗?从示例来看,似乎不可以。width_ratios参数也不起作用,因为这会影响所有行。

  1. import matplotlib.pyplot as plt
  2. from matplotlib.gridspec import GridSpec
  3. fig = plt.figure(figsize=(10, 6))
  4. gs = GridSpec(2, 3)
  5. # First row (1.5 column width)
  6. ax1 = plt.subplot(gs[0, 0])
  7. ax2 = plt.subplot(gs[0, 1])
  8. # Second row (one-third width)
  9. ax3 = plt.subplot(gs[1, 0])
  10. ax4 = plt.subplot(gs[1, 1])
  11. ax5 = plt.subplot(gs[1, 2])
  12. ax1.set_title('Subplot 1')
  13. ax2.set_title('Subplot 2')
  14. ax3.set_title('Subplot 3')
  15. ax4.set_title('Subplot 4')
  16. ax5.set_title('Subplot 5')
  17. plt.tight_layout()
  18. plt.show()

上面的代码产生了这个。我只是不知道如何使子图1和2跨越1.5列。

44u64gxh

44u64gxh1#

使用subplot_mosaic

  1. axd = plt.figure(layout='constrained', figsize=(10,6)).subplot_mosaic(
  2. """
  3. AAABBB
  4. CCDDEE
  5. """
  6. )
  7. for i, ax in enumerate(axd.values(), start=1):
  8. ax.set_title(f'Subplot {i}')
  9. plt.show()

输出:

z9ju0rcb

z9ju0rcb2#

你可能会想做一个2x6网格:

  1. fig = plt.figure(figsize=(10, 6))
  2. gs = GridSpec(2, 6)
  3. # First row (1.5 column width)
  4. ax1 = plt.subplot(gs[0, :3])
  5. ax2 = plt.subplot(gs[0, 3:])
  6. # Second row (one-third width)
  7. ax3 = plt.subplot(gs[1, :2])
  8. ax4 = plt.subplot(gs[1, 2:4])
  9. ax5 = plt.subplot(gs[1, 4:])
  10. ax1.set_title('Subplot 1')
  11. ax2.set_title('Subplot 2')
  12. ax3.set_title('Subplot 3')
  13. ax4.set_title('Subplot 4')
  14. ax5.set_title('Subplot 5')
  15. plt.tight_layout()

产出:

展开查看全部

相关问题