如何 select 子图中指定子图中的图例句柄和标签?

How to select legend handles and labels from specified subplots inside of subplots?

我有一个子图的子图。外部子图由一行两列组成,两个内部子图各由四行四列组成。假设我想要仅对应于第一个 2x2 内部子图的图例标签。我该怎么做呢?我的尝试如下:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

outerD = dict(nrows=1, ncols=2)
innerD = dict(nrows=2, ncols=2)
D = dict(inner=innerD, outer=outerD)

def initialize_dubsub(D, figsize=None):
    """ """
    fig = plt.figure(figsize=figsize)
    outerG = gridspec.GridSpec(D['outer']['nrows'], D['outer']['ncols'], wspace=0.2, hspace=0.2, width_ratios=[5, 5])
    axes = []
    for n in range(D['inner']['nrows']):
        inner = gridspec.GridSpecFromSubplotSpec(D['inner']['nrows'], D['inner']['ncols'], subplot_spec=outerG[n], wspace=0.25, hspace=0.3, width_ratios=[10, 10], height_ratios=[2, 2])
        for m in range(D['inner']['nrows']*D['inner']['ncols']):
            ax = plt.Subplot(fig, inner[m])
            ax.plot([], [], label='{}x{}'.format(n, m))
            ax.set_xticks([])
            ax.set_yticks([])
            axes.append(ax)
            fig.add_subplot(ax)
    # handles, labels = axes[:4].get_legend_handles_labels() # first 2x2
    # fig.legend(handles=handles, labels=labels, loc='lower center')
    fig.legend(loc='lower center', ncol=4, mode='expand')
    plt.show()
    plt.close(fig)

initialize_dubsub(D)

此代码将输出 8 handles8 labels,而我想要每个 4。我注释掉了 get_legend_handles_labels() 方法,因为它不适用于数组。

我知道我可以 ax.legend() 但我更喜欢使用 fig.legend(...)。我怎样才能做到这一点?

与其尝试在所需的子图数组上调用 .get_legend_handles_labels,不如循环遍历该数组中的轴,并将这四个子图的句柄和标签附加到列表中。

例如:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

outerD = dict(nrows=1, ncols=2)
innerD = dict(nrows=2, ncols=2)
D = dict(inner=innerD, outer=outerD)

def initialize_dubsub(D, figsize=None):
    """ """
    fig = plt.figure(figsize=figsize)
    outerG = gridspec.GridSpec(D['outer']['nrows'], D['outer']['ncols'], wspace=0.2, hspace=0.2, width_ratios=[5, 5])
    axes = []
    for n in range(D['inner']['nrows']):
        inner = gridspec.GridSpecFromSubplotSpec(D['inner']['nrows'], D['inner']['ncols'], subplot_spec=outerG[n], wspace=0.25, hspace=0.3, width_ratios=[10, 10], height_ratios=[2, 2])
        for m in range(D['inner']['nrows']*D['inner']['ncols']):
            ax = plt.Subplot(fig, inner[m])
            ax.plot([], [], label='{}x{}'.format(n, m))
            ax.set_xticks([])
            ax.set_yticks([])
            axes.append(ax)
            fig.add_subplot(ax)
    handles, labels = [], []
    for ax in axes[:4]:
        handles_, labels_ = ax.get_legend_handles_labels()
        handles += handles_
        labels += labels_
    fig.legend(handles=handles, labels=labels, loc='lower center')
    #fig.legend(loc='lower center', ncol=4, mode='expand')
    plt.show()
    plt.close(fig)

initialize_dubsub(D)

尝试替换

ax.plot([], [], label='{}x{}'.format(n, m))

来自

ax.plot([], [], label=('' if n==0 else '_') + '{}x{}'.format(n, m))

如果我理解你的设置正确...