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

2024-06-23 03:15:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用GridSpec控制4x 1网格的纵横比。我想在水平方向上画很宽的图,在垂直方向上画紧凑的图,但是我不能预测地改变纵横比(见第一张图)。下面的三个“高度比”设置都给出了相同的长宽比(见下面的第二张图片):

一:

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


Tags: gs空间plt方向widthheightsetaspect
1条回答
网友
1楼 · 发布于 2024-06-23 03:15:06

您需要设置图形大小,以便获得所需的纵横比,这是通过plt.figurefigsize参数控制的。在这个例子中,不清楚您是否真的需要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方法。

相关问题 更多 >

    热门问题