繁体   English   中英

Matplotlib:外部图例,分布在多个子图上

[英]Matplotlib: External legend, spread across multiple subplots

我有一个带有2个子图的图,所有图都共享相应的图,即相同颜色的相同标签。 我希望在图的顶部有一个图例,延伸到两个子图上。 与以下代码类似:

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-1,1,1000)
y1 = x
y2 = 0.1*x**2
y3 = x**3
y4 = x**4
y5 = x**5

fig, grid = plt.subplots(1,2,sharex="col", sharey="row")
fig.subplots_adjust(wspace=0, hspace=0)
grid[0].plot(x,y1, label='1')
grid[0].plot(x,y2, label='2')
grid[0].plot(x,y3, label='3')
grid[0].plot(x,y4, label='4')
grid[0].plot(x,y5, label='5')
grid[1].plot(x,y1, label='1')

grid[0].legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=5, borderaxespad=0.)
plt.show()

这个例子看起来很不错。 唯一的问题是图例从第一个图的开头延伸到第二个图的中间。 但是,我希望这个图例可以延伸到两个图上。 我怎样才能做到这一点?

注意:原始问题使用2x3网格(2行,3列)。

原则上, 如何将图例从情节中删除,特别是这篇文章适用。 这里一个简单的解决方案是使用图形的子图参数来确定图例的图形坐标中的边界框,并使用mode="expand"

bb = (fig.subplotpars.left, fig.subplotpars.top+0.02, 
      fig.subplotpars.right-fig.subplotpars.left,.1)

grid[0].legend(bbox_to_anchor=bb, mode="expand", loc="lower left",
               ncol=5, borderaxespad=0., bbox_transform=fig.transFigure)

在此输入图像描述

您可以尝试使用figlegend类的figlegend

fig, grid = plt.subplots(1,2,sharex="col", sharey="row")
fig.subplots_adjust(wspace=0, hspace=0)
a = grid[0].plot(x,y1)
b = grid[0].plot(x,y2)
c = grid[0].plot(x,y3)
d = grid[0].plot(x,y4)
e = grid[0].plot(x,y5)
f = grid[1].plot(x,y1)

fig.legend((a[0], b[0], c[0], d[0], e[0]), ('label 1', 'label 2', 'label 3', 'label 4', 'label 5'), 'upper center', ncol = 5)
plt.show()

变量a, b, c, d, e, f是具有Line2D类型的单个对象的列表。 或者,您可以继续按照您已完成的方式分配标签,然后像这样调用该属性

fig.legend((a[0], b[0], c[0], d[0], e[0]), (a[0]._label, b[0]._label, c[0]._label, d[0]._label, e[0]._label), 'upper center', ncol = 5)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM