Matplotlib 迭代设置子图轴大小

Matplotlib set subplot axis size iteratively

有几个相关问题 (here, here, and ),但建议的解决方案对我的情况不起作用。

我正在迭代创建子图,所以我不知道每个子图的宽度(它是在调用 plt.subplots() 之后计算的),这意味着我无法设置我最初创建它们时每个子图的大小。 我想在创建子图 x 轴后设置它的大小。

想象一下:

items = [A,B,C]  #this could have any number of items in it
f,ax = plt.subplots(len(items),1, figsize=(10,10)) #figsize is arbitrary and could be anything

for i in range(len(items)):
    #calculate x and y data for current item
    #calculate width of x axis for current item
    plt.sca(ax[i])
    cax = plt.gca()
    cax.plot(x,y)
    #here is where I would like to set the x axis size
    #something like cax.set_xlim(), but for the size, not the limit

注1:单位无关紧要,但相对大小很重要,所以它可以是像素大小,也可以是厘米大小,甚至可以是根据相对宽度计算出的比率。

注意 2:在这种情况下,x 轴的宽度与 x 限制无关,因此我不能只设置 x 限制并期望轴正确缩放。

此外,我尽量让这段代码简短,因为它要与不熟悉 Python 的人共享,所以如果唯一的解决方案涉及添加一堆行,那是不值得的,我将忍受不正确缩放的轴。这是一种审美偏好,但不是必需的。 谢谢!

编辑:这就是我的目标

您可以创建一个新的 GridSpec 指定 height_ratios,然后更新每个 ax 的位置:

import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec

# create figure
f, ax = plt.subplots(3, 1, figsize=(10,10))

# plot some data
ax[0].plot([1, 2, 3])
ax[1].plot([1, 0, 1])
ax[2].plot([1, 2, 20])

# adjust subplot sizes
gs = GridSpec(3, 1, height_ratios=[5, 2, 1])
for i in range(3):
    ax[i].set_position(gs[i].get_position(f))

plt.show()

我之前问过类似的问题。用例略有不同,但可能仍然有用。

现在您肯定得到了答案,或者这个问题已被弃用,但如果其他人正在搜索,我使用“Bbox”解决了这个问题。这个想法是这样的:

from matplotlib.transforms import Bbox

fig, ax = plt.subplots(3,1, figsize = (11,15))
ax[0].set_position(Bbox([[0.125, 0.6579411764705883], [0.745, 0.88]]))
ax[2].set_position(Bbox([[0.125, 0.125], [0.745, 0.34705882352941175]]))

有关详细信息,请查看 https://matplotlib.org/api/transformations.html#matplotlib.transforms.Bbox