简体   繁体   English

如何保存在matplotlib.pyplot中显示的图?

[英]How to savefig as show in matplotlib.pyplot?

I'm using matplotlib.pyplot to draw a bar chart with a legend, the figure saved by plt.savefig() is incomplete compared to plt.show() . 我正在使用matplotlib.pyplot绘制带有图例的条形图,与plt.savefig()相比, plt.show()保存的数字不完整。 To be more precise, the legend is out of the plot, the jpg file only have the leftside half of the legend. 更准确地说,图例不在图例中,jpg文件仅包含图例的左侧一半。

My codes: 我的代码:

from matplotlib import pyplot as plt
fig = plt.figure(figsize=(12,6))
plt.bar(x, y, label="a")
plt.legend(bbox_to_anchor=(1.02, 1), loc="upper left")
plt.show()
fig.savefig("a.jpeg")

I looked through this answer Matplotlib savefig with a legend outside the plot but the chosen answer suggest to adjust the axis manually. 我通过这个答案在Matplotlib savefig中查找了图例外的图例,但是选择的答案建议手动调整轴。 I have many different figures so that may be inappropriate. 我有许多不同的数字,因此可能不合适。 Since it was posted years ago, I wonder whether any automatic method could be used to make the effect of plt.savefig() as plt.show() ? 自从它在几年前发布以来,我想知道是否可以使用任何自动方法来使plt.savefig()效果像plt.show() I couldn't find any appropriate argument for that in plt.savefig() . 我在plt.savefig()找不到适合的参数。

Thanks! 谢谢!

希望这能解决问题。在参数中添加bbox_inches='tight'有助于消除空格

 fig.savefig('a.jpeg', bbox_inches='tight', pad_inches=0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM