python - Matplotlib迭代设置子图轴大小

标签 python matplotlib scaling subplot axes

有几个相关问题( 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 的人共享,所以如果唯一的解决方案涉及添加一堆行,那么这是不值得的,而且我将忍受错误缩放轴。这是一种审美偏好,但不是必需的。 谢谢!

编辑:这就是我的目标 desired subplots

最佳答案

您可以创建一个新的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()

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

关于python - Matplotlib迭代设置子图轴大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53521778/

相关文章:

python - 使用正则表达式过滤 pandas

python - 从 shell 命令获取输出的最 Pythonic 方法

python - 在 Matlab 中对于矩阵(m,n)等效矩阵(:) , 冒号,在 python 中

python - Matplotlib 图形上的多条线

java - (DPI) 在 Java Swing(和 Windows)中缩放字体

python - 将 MailChimp 与 SendGrid 结合使用

python - 如何为我的数据创建条形图?

python - 拆分管道分隔的系列,按单独的系列分组,并返回新列中每个拆分值的计数

model - 如何在 libgdx 中先缩放然后旋转模型实例

c++ - 缩放和插值数组