【问题标题】:Add axes to a figure with a fixed size将轴添加到具有固定大小的图形
【发布时间】:2021-02-23 09:39:36
【问题描述】:

我想创建一个图,其中子图在 for 循环中动态添加。应该可以以厘米为单位定义每个子图的宽度和高度,也就是说,添加的子图越多,图形就需要越大,以便为“传入”子图腾出空间。

在我的例子中,子图应该逐行添加,这样数字必须在 y 维度上变大。我遇到了这个stackoverflow post,这可能会导致正确的方向?也许gridspec module 也可以解决这个问题?

我尝试了第一篇文章中描述的代码,但这不能解决我的问题(它设置了最终的图形大小,但是添加到图形中的子图越多,每个子图变得越小,如下所示示例):

import matplotlib.pyplot as plt

# set number of plots
n_subplots = 2

def set_size(w,h,ax=None):
    """ w, h: width, height in inches """
    if not ax: ax=plt.gca()
    l = ax.figure.subplotpars.left
    r = ax.figure.subplotpars.right
    t = ax.figure.subplotpars.top
    b = ax.figure.subplotpars.bottom
    figw = float(w)/(r-l)
    figh = float(h)/(t-b)
    ax.figure.set_size_inches(figw, figh)

fig = plt.figure()

for idx in range(0,n_subplots):
    ax = fig.add_subplot(n_subplots,1,idx+1)
    ax.plot([1,3,2])
    set_size(5,5,ax=ax)

plt.show()

【问题讨论】:

    标签: matplotlib plot


    【解决方案1】:

    无论子图的数量如何,您都设置了相同的图形大小 (5,5)。如果我正确理解了您的问题,我认为您希望将高度设置为与子图的数量成正比。

    但是,您最好从一开始就创建尺寸合适的人物。您提供的代码提供了正确的布局,只是因为您事先知道要创建多少个子图(在fig.add_subplot(n_subplots,...) 中)。如果您在不知道所需的子图行总数的情况下尝试添加子图,则问题会更加复杂。

    n_subplots = 4
    
    ax_w = 5
    ax_h = 5
    dpi = 100
    
    fig = plt.figure(figsize=(ax_w, ax_h), dpi=dpi)
    
    for idx in range(0,n_subplots):
        ax = fig.add_subplot(n_subplots,1,idx+1)
        ax.plot([1,3,2])
    fig.set_size_inches(ax_w,ax_h*n_subplots)
    fig.tight_layout()
    

    【讨论】:

    • fig.set_size_inches(ax_w,ax_h*n_subplots) 解决了!
    猜你喜欢
    • 2019-02-13
    • 1970-01-01
    • 2013-09-07
    • 2019-08-01
    • 2023-03-28
    • 2021-11-24
    • 1970-01-01
    • 2016-08-28
    • 2012-03-31
    相关资源
    最近更新 更多