【问题标题】:matplotlib: get the subplot layout?matplotlib:获取子图布局?
【发布时间】:2016-01-02 19:57:31
【问题描述】:

我有一个创建类似二维直方图网格的函数。为了让我可以选择是否将这个新图放在预先存在的图形上,我执行以下操作:

def make_hist2d(x, y, current_fig=False, layout=(1,1,1),*args):

    if current_fig: 

        fig = _plt.gcf()
        ax  = fig.add_subplot(*layout)  # layout=(nrows, ncols, nplot)

    else:

        fig, ax = _plt.subplots()    


    H, x, y = np.histogram2d(...)

    # manipulate the histogram, e.g. column normalize.

    XX, YY = _np.meshgrid(xedges, yedges)
    Image  = ax.pcolormesh(XX, YY, Hplot.T, norm=norm, **pcmesh_kwargs)
    ax.autoscale(tight=True)

    grid_kargs = {'orientation': 'vertical'}
    cax, kw    = _mpl.colorbar.make_axes_gridspec(ax, **grid_kargs)
    cbar       = fig.colorbar(Image, cax=cax)
    cbar.set_label(cbar_title)

    return fig, ax, cbar



def hist2d_grid(data_dict, key_pairs, layout, *args):  # ``*args`` are things like xlog, ylog, xlabel, etc. 
                                                       # that are common to all subplots in the figure.

    fig, ax = _plt.subplots()    

    nplots = range(len(key_pairs) + 1)    # key_pairs = ((k1a, k1b), (k2a, k2b), ..., (kna, knb))

    ax_list = []

    for pair, i in zip(key_pairs, nplots):

        fig, ax, cbar = make_hist2d(data[k1a], data[k1b]

        ax_list.append(ax)

    return fig, ax_list

然后我调用类似的东西:

hgrid = hist2d_grid(...)

但是,如果我想向grid 添加一个新图形,我不知道获得子图布局的好方法。例如,是否有类似的内容:

layout = fig.get_layout()

那会给我类似(nrows, ncols, n_subplots)的东西?

我可以这样做:

n_plot = len(ax_list) / 2  # Each subplot generates a plot and a color bar.
n_rows = np.floor(np.sqrt(n_ax))
n_cols = np.ceil(np.sqrt(n_ax))

但我必须处理像(2,4) 子图数组这样的特殊情况,我会得到n_rows = 2n_cols = 3,这意味着我会将(2,3,8) 传递给ax.add_subplot(),这显然不会不能工作,因为 8 > 3*2。

【问题讨论】:

    标签: layout matplotlib figure subplot


    【解决方案1】:

    由于fig, ax = plt.subplots(4,2)返回的ax是一个numpy轴数组,那么ax.shape会给你你想要的布局信息,例如

     nrows, ncols = ax.shape
     n_subplots = nrows*ncols
    

    您还可以通过遍历图形对象的子对象来获取各个轴的位置,

    [[f.colNum, f.rowNum] for f in fig.get_children()[1:]]
    

    并且可能从最终元素fig.get_children()[-1]中获取大小

    如果需要,您还可以使用gridspec 更明确地了解子图的位置。使用 gridspec 设置 gridspec 对象并传递给 subplot,

    import matplotlib.gridspec as gridspec
    gs = gridspec.GridSpec(2, 2)
    ax = plt.subplot(gs[0, 0])
    

    为了得到你可以使用的布局,

    gs.get_geometry()
    

    【讨论】:

    • 好点。我可以设置一个gridspec 并且只根据需要添加轴。
    猜你喜欢
    • 2021-06-14
    • 2018-12-14
    • 2021-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-23
    • 1970-01-01
    • 2011-05-03
    相关资源
    最近更新 更多