阅读以下文章后,我成功地将图例放在了绘图之外。
代码:
import matplotlib.pyplot as pyplot
x = [0, 1, 2, 3, 4]
y = [xx*xx for xx in x]
fig = pyplot.figure()
ax = fig.add_subplot(111)
box = ax.get_position()
ax.set_position([box.x0, box.y0, box.width*0.8, box.height])
ax.plot(x, y)
leg = ax.legend(['abc'], loc = 'center left', bbox_to_anchor = (1.0, 0.5))
#pyplot.show()
fig.savefig('aaa.png', bbox_inches='tight')
pyplot.show()
显示具有位于外部的图例的正确图形。但是当我使用 fig.savefig()
将其保存为文件时,图例被截断。
一些谷歌搜索向我展示了解决方法,例如在 savefig()
中添加 bbox_extra_artists=[leg.legendPatch]
或 bbox_extra_artists=[leg]
,但两者都没有起作用。
正确的方法是什么?Matplotlib 版本为 0.99.3。
谢谢。
plt.savefig(path_output, bbox_inches='tight')
中添加bbox_inches='tight'
对我很有效。在保存之前,我设置了fig.legend(lines, labels, bbox_to_anchor=(0, 1, 1, 0), loc="lower left", mode="expand", ncol=4); plt.tight_layout();
。因此图例位于绘图的顶部。 - FisNaN