将图例扩展到 2 个子图

Expanded legend over 2 subplots

我怎样才能让相同的图例出现在 2 个子图中并使其扩展到 2 个子图中。有人知道吗,如果每个子图相同(情节是一篇科学论文)?我知道后一个问题与计算无关,但如果有人知道答案,我将不胜感激。

我使用的图例位置:

        ax[0].legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
               ncol= 4, mode="expand", borderaxespad=0)

要使图例跨越两个子图,您需要调整给定 bbox_to_anchor 的坐标。使用 2.2 作为宽度(第三个参数)覆盖图宽度的 2 倍加上子图之间的间距。 (如果您的间距与默认间距不同,例如 f.tightlayout(),则需要调整此值。)

这是一个简单的工作示例:

import numpy as np
import matplotlib.pyplot as plt

x1 = np.linspace(0.0, 2.0)
x2 = np.linspace(0.0, 2.0)

y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
y2 = np.cos(2 * np.pi * x2)

f,ax = plt.subplots(1, 2)

ax[0].plot(x1, y1, 'ko-', label='Damped')
ax[0].plot(x2, y2, 'r.-', label='Undamped')
ax[1].plot(x1, y1, 'ko-', label='Damped')
ax[1].plot(x2, y2, 'r.-', label='Undamped')

ax[0].legend(bbox_to_anchor=(0., 1.02, 2.2, .102), loc=3,
               ncol=4, mode="expand", borderaxespad=0)

plt.show()

结果是这个情节:

要在图中的所有子图中拉伸图例,您可以半自动化图例放置。使用图中的 subplotpars 可以找到使用的间距,这样这些间距就可以直接用在 bbox_to_anchor 参数中。这需要通过 bbox_transform 参数将图例变换设置为图形变换。您需要手动指定的唯一参数是轴和图例之间的间距(下例中的 0.02)和图例的高度(下例中的 0.05),均以图形高度为单位。

s = fig.subplotpars
bb=[s.left, s.top+0.02, s.right-s.left, 0.05 ]
leg = axes[0].legend(..., bbox_to_anchor=bb, mode="expand", borderaxespad=0,
                     bbox_transform=fig.transFigure)

完整示例:

import matplotlib.pyplot as plt
import numpy as np

a = np.cumsum(np.random.rand(10,8), axis=0)

fig, axes = plt.subplots(ncols=2)

for i in range(a.shape[1]):
    axes[i//4].plot(a[:,i], marker="s", label="Label {}".format(i))

s = fig.subplotpars
bb=[s.left, s.top+0.02, s.right-s.left, 0.05 ]
leg = axes[0].legend(loc=8, bbox_to_anchor=bb, ncol= 4, mode="expand", borderaxespad=0,
                bbox_transform=fig.transFigure, fancybox=False, edgecolor="k")
leg.get_frame().set_linewidth(72./fig.dpi)
plt.show()

至于一篇科学论文需要一个还是两个图例,这完全取决于论文的风格。我猜想使用像这里这样的单个图例就可以了。然而,期刊大多要求您用小写字母标记每个子图,例如 ab(a)(b).