Python 相对于multiplot中图形的Matplotlib图例

Python 相对于multiplot中图形的Matplotlib图例,python,matplotlib,legend,subplot,Python,Matplotlib,Legend,Subplot,我想将一个具有多个子图形的图形的图例移动到相对于整个图形的上中心。我试图使用bbox\u extra\u artist将使用fig.legend创建的图例对象传递到fig.savefig,如前所述。但是,与前面描述的不同,图例被截断: 这是我使用的代码: import matplotlib.pyplot as plt import numpy as np x = np.arange(-2*np.pi, 2*np.pi, 0.1) fig, axes = plt.subplots(nrows=

我想将一个具有多个子图形的图形的图例移动到相对于整个图形的上中心。我试图使用
bbox\u extra\u artist
将使用
fig.legend
创建的图例对象传递到
fig.savefig
,如前所述。但是,与前面描述的不同,图例被截断:

这是我使用的代码:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(-2*np.pi, 2*np.pi, 0.1)
fig, axes = plt.subplots(nrows=5, ncols=3, sharex=True, sharey=False)
legendLines = []
for rI, rA in enumerate(axes):
    for cI, ax in enumerate(rA):
        line, = ax.plot(x, np.sin(x), label='Sine')
        legendLines.append(line)
        line, = ax.plot(x, np.cos(x), label='Cosine')
        legendLines.append(line)
        line, = ax.plot(x, np.arctan(x), label='Inverse tan')
        legendLines.append(line)
        if cI == 0:
            ax.set_ylabel('foo')
        if rI == len(axes) -1:
            ax.set_xlabel('bar')
        if rI == 0:
            ax.set_title('baz')

legend = fig.legend(legendLines[:3], ['Sine', 'Cosine', 'Inverse Tan'], 'upper center', frameon=False, ncol=3, borderaxespad=-0.7)
outFile = 'test.pdf'
fig.set_size_inches(8,7)
fig.tight_layout()
fig.savefig(outFile, bbox_extra_artists=[legend], bbox_inches='tight')
plt.close()
我正在寻找一种技术,可以让我定义相对于整个图形的图例位置,而不仅仅是一个子图形

更新:

如果我替换

legend = fig.legend(legendLines[:3], ['Sine', 'Cosine', 'Inverse Tan'], 'upper center', frameon=False, ncol=3, borderaxespad=-0.7)

结果是一样的:绘图区域没有增加,图例从绘图中移出


(系统:matplotlib-1.2.0-py2.7-macosx-10.8-intel)

如果将生成图例的行替换为以下行:

legend = fig.legend(legendLines[:3], ['Sine', 'Cosine', 'Inverse Tan'], loc='lower center', frameon=False, ncol=3, bbox_to_anchor=(.5, 1.))
一切似乎都很好

即使
bbox\u to\u anchor=(0.5,1.5)
图例也会保存到pdf格式:


这可能意味着将matplotlib更新到最新版本可能会解决问题。

更新到最新的
matplotlib
1.4.3版解决了问题。

您可以粘贴以下内容的输出:
plt.rcParams['savefig.pad_inches']
plt.rcParams['savefig.pad_inches']的输出是
0.1
(绘图前后)很抱歉,无法再现此问题…无论图例被推到离ax有多远,它都可以通过
savefig
正确捕获。您可能希望尝试增加填充,将此添加到
savefig
pad_inches=1
(但这似乎不太可能是解决方案).数字越高,图中的所有内容就越多。请参见我答案中的示例。嗯……似乎对您有效。您能告诉我您的操作系统和python/matplotlib版本吗?Thx@PrimerOSX 10.10.2、matplotlib 1.4.3、python 3.4.3.你是说即使使用
borderaxespad=-0.7而不使用
bbox\u-to\u-anchor
fig.legend
的参数中,您能够在pdf中完整捕获图例?因为它对我不起作用。我猜
bbox\u-to\u-anchor
是一种方法。但是,
loc='upper center',frameon=False,ncol=3,borderaxespad=0
没有
bbox-to\u-anchor
也给出了期望值ed结果。谢谢你的提示!
legend = fig.legend(legendLines[:3], ['Sine', 'Cosine', 'Inverse Tan'], loc='lower center', frameon=False, ncol=3, bbox_to_anchor=(.5, 1.))