我正在尝试制作一个图像,其中我将图例放在轴线之外。但是我发现,如果我在plt.savefig()方法中使用bbox_inches='tight',生成的图像将不包含图例。要说明的最小工作示例如下:
import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl
x = np.arange(-5, 5, 0.1)
y1 = np.sin(x)
y2 = np.cos(x)
fig, ax1= plt.subplots(ncols=1, nrows=1, figsize=(10, 6))
ax1.plot(x, y1, label='sin(x)')
ax1.plot(x, y2, label='cos(x)')
handles, labels = ax1.get_legend_handles_labels()
plt.figlegend(handles, labels, loc='upper left', ncol=2, frameon=False,
bbox_to_anchor=(0.11, 0.95))
plt.savefig('test.jpg', bbox_inches='tight')生成的test.jpg如下所示

如果我在savefig()方法中删除bbox_inches='tight'。(如下所示),图例出现在生成的图像中,但在图像的四边有两个很大的空白。

有没有好的方法来保留图像的紧凑布局,同时在生成的图像中保留图例?
编辑1
按照this post中的说明,我还尝试在savefig()方法中使用bbox_extra_artists参数,如下所示
legend = plt.figlegend(handles, labels, loc='lower left', ncol=2, frameon=True,
bbox_to_anchor=(0.12, 0.88))
plt.savefig('test.jpg', bbox_extra_artists=(legend,), bbox_inches='tight')正如@Diziet Asahi和@mportanceOfBeingErnest所指出的那样,如果我们使用ax.legend()方法,一切都会正常工作。下面的代码可以工作,
legend = ax1.legend(handles, labels, ncol=2, frameon=False,
loc='lower left', bbox_to_anchor=(-0.01, 1.2))
plt.savefig('test.jpg', bbox_inches='tight')Edit2
According to the Matplotlib developer,当我们使用紧凑的布局时,似乎有一个由fig.legend方法产生的图例没有被考虑在内的错误。
发布于 2018-01-08 18:46:31
您可以使用图形的一个轴的.legend()方法创建图例。为了在地物坐标中指定图例坐标,可以使用bbox_transform参数,这将使用figlegend来完成。
ax1.legend(handles, labels, loc='upper left', ncol=2, frameon=False,
bbox_to_anchor=(0.11, 0.95), bbox_transform=fig.transFigure)发布于 2018-01-08 05:09:03
我不能确切地说出为什么会发生这种情况(对我来说似乎是一个错误),但看起来问题出在您使用顶级plt.figlegend()函数时。如果使用Figure.legend(),该问题仍然存在,但如果使用Axes.legend()替换,则该问题会消失
legend = ax1.legend(handles, labels, loc='lower left', ncol=2, frameon=False,
bbox_to_anchor=(0,1.2))
fig.savefig('test.jpg', bbox_extra_artists=[legend], bbox_inches='tight')

https://stackoverflow.com/questions/48128546
复制相似问题