Python/Matplotlib:在gridspec中控制纵横比

4 投票
1 回答
11182 浏览
提问于 2025-04-18 07:19

我正在尝试使用GridSpec来控制一个4 x 1的网格的宽高比。我想要的是横向的图很宽,而纵向的图比较紧凑,但我无法预测地改变宽高比(见第一张图片)。下面的‘height_ratios’的三种设置都给了我相同的宽高比(见第二张图片):

第一种:

gs = gridspec.GridSpec(4, 1, width_ratios=[1], height_ratios=[0.1, 0.1, 0.1, 0.1])
gs.update(wspace = 0, hspace = 0)

ax1 = plt.subplot(gs[0])
ax2 = plt.subplot(gs[1])
ax3 = plt.subplot(gs[2])
ax4 = plt.subplot(gs[3])

plt.show()

第二种:

gs = gridspec.GridSpec(4, 1, width_ratios=[1], height_ratios=[1, 1, 1, 1])

第三种:

gs = gridspec.GridSpec(4, 1, width_ratios=[1], height_ratios=[0.5, 0.5, 0.5, 0.5])

我通过这样做得到了我想要的拉长图:

ax1.set_aspect(0.1)
ax2.set_aspect(0.1)
ax3.set_aspect(0.1)
ax4.set_aspect(0.1)

但这样在子图之间增加了空间,我不想要这个,所以我用hspace = 0去掉了。请问我怎么能控制宽高比而不在子图之间增加空间呢?

这是我想要的效果,但我似乎无法再次实现,不知道为什么:

enter image description here

相反,我得到的却是这个:

enter image description here

这是我使用ax.set_aspect(0.1)得到的效果,宽高比是正确的,但它在图之间引入了空间,我不想要这个:

enter image description here

1 个回答

5

你需要设置图形的大小,这样才能得到你想要的比例,这个比例是通过 figsize 参数在 plt.figure 中控制的。在这个例子里,其实不太清楚你是否真的需要用到 GridSpec; 我会这样做:

import matplotlib.pyplot as plt

f, axes = plt.subplots(4, 1, figsize=(10, 4))
f.subplots_adjust(hspace=0)

enter image description here

如果你确实需要使用 GridSpec 来处理更复杂的布局,你可以先用 plt.figure 创建图形,然后把网格的切片传递给返回对象的 add_subplot 方法。

撰写回答