Matplotlib:获取子图布局?

3

我有一个函数可以创建类似2D直方图的网格。为了选择是否将此新绘图放置在预先存在的图中,我执行以下操作:

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()

那么这将会给我得到类似于(行数,列数,子图数量)的结果?

我可以用以下方式实现:

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。
1个回答

3

当使用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,只在需要时添加轴。 - blalterman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接