首页 > 解决方案 > Matplotlib 迭代设置子图轴大小

问题描述

有几个相关的问题(hereherehere),但建议的解决方案不适用于我的情况。

我正在迭代地创建子图,所以我不提前知道每个子图的宽度(在调用 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 的人共享的,所以如果唯一的解决方案涉及添加一堆行,那是不值得的,我会忍受不正确缩放的轴。这是一种审美偏好,但不是要求。谢谢!

编辑:这就是我的目标 所需的子图

标签: pythonmatplotlibscalingsubplotaxes

解决方案


现在你肯定得到了答案,或者这个问题已被弃用,但如果其他人正在搜索,我使用“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


推荐阅读