使用fig.legend且bbox_inches='tight'时图例消失的问题咨询
解决Matplotlib中
bbox_inches='tight'导致fig.legend()图例丢失的问题 这是Matplotlib里挺常见的小坑——当你用plt.figlegend()把图例放在坐标轴外,同时用bbox_inches='tight'保存图像时,图例会被裁剪掉;但去掉这个参数又会留下大量留白。下面给你两个可行的解决办法:
方法1:用bbox_extra_artists手动让tight布局包含图例
在调用plt.savefig()时,把图例对象传入bbox_extra_artists参数,这样tight布局计算时就会把图例的尺寸也考虑进去,不会再裁剪它。示例代码如下:
import matplotlib.pyplot as plt import numpy as np 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() # 先将图例赋值给变量,方便后续传入参数 legend = plt.figlegend(handles, labels, loc='upper left', ncol=2, frameon=False, bbox_to_anchor=(0.11, 0.95)) # 保存时指定bbox_extra_artists为图例对象 plt.savefig('test.jpg', bbox_extra_artists=(legend,), bbox_inches='tight')
方法2:改用坐标轴的legend()方法替代fig.legend()
如果你的图例只属于单个坐标轴,直接用坐标轴对象的ax.legend()方法来创建和放置图例更可靠,tight布局会自动识别并包含这个图例,不需要额外配置。示例代码:
import matplotlib.pyplot as plt import numpy as np 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() # 使用ax1.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')
背后的原因
根据Matplotlib开发者的说法,这其实是一个已知的bug:当使用tight布局时,fig.legend()生成的图例没有被纳入tight布局的计算范围,导致保存图像时被误裁剪。上面的两种方法都是绕过这个bug的有效方案。
内容的提问来源于stack exchange,提问作者jdhao
相关产品推荐
相关产品推荐

