如果我使用fig.legend方法对bbox_inches使用"tight",为什么图例在生成的图像中不存在? [英] why is the legend not present in the generated image if I use 'tight' for bbox_inches with the fig.legend method?
问题描述
我正在尝试生成将图例放在轴外的图像.但是我发现,如果在plt.savefig()
方法中使用bbox_inches='tight'
,则生成的图像将不包含图例.一个最小的工作示例可以说明如下:
I am trying to produce an image where I put the legend outside of the axes. But I find that if I use bbox_inches='tight'
in the plt.savefig()
method, the generated image does not contain the legend. A minimal working example to illustrate is as follows:
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'
(如下所示),则图例出现在生成的图像中,但是图像的四个侧面有两个空白.
If I remove bbox_inches='tight'
in savefig()
method.(shown below), the legend is present in the produced image , but there are two much white space in the four side of the image.
是否有很好的方法可以保留图像的紧凑布局,并在生成的图像中保留图例?
Is there a good way to retain the tight layout of the image and also retain the legend in the generated image?
Following the instruction in this post, I also tried to use bbox_extra_artists
argument in the savefig()
method, something like this
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()
方法,则一切正常.以下代码有效,
As is pointed by @Diziet Asahi and @mportanceOfBeingErnest, if we use ax.legend()
method, everything works fine. The following code works,
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
根据Matplotlib开发人员,似乎有一个图例产生的错误当我们使用紧凑的布局时,不会考虑使用fig.legend
方法的方法.
Edit2
According to the Matplotlib developer, there seems to be a bug that legend produced by fig.legend
method are not taken into account when we use tight layout.
推荐答案
您可以使用图形轴之一的.legend()
方法创建图例.为了在图形坐标中指定图例坐标,如使用figlegend
一样,可以使用bbox_transform
参数.
You may create the legend using the .legend()
method of one of the figure's axes. In order to specify the legend coordinates in figure coordinates, as would be done using figlegend
you may use the bbox_transform
argument.
ax1.legend(handles, labels, loc='upper left', ncol=2, frameon=False,
bbox_to_anchor=(0.11, 0.95), bbox_transform=fig.transFigure)
这篇关于如果我使用fig.legend方法对bbox_inches使用"tight",为什么图例在生成的图像中不存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!