5

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(). To be more precise, the legend is out of the plot, the jpg file only have the leftside half of the legend.

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. 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()? I couldn't find any appropriate argument for that in plt.savefig().

Thanks!

Community
  • 1
  • 1
Kaho Chan
  • 355
  • 1
  • 3
  • 9
  • 1
    Does adding `bbox_inches='tight'` to savefig solve the problem? – Ed Smith Aug 18 '16 at 08:20
  • Thanks! That help. But I don't quite understand the comment in the docs about `bbox_inches`. What's it for? – Kaho Chan Aug 18 '16 at 08:24
  • It is meant to simply removes white space, although I've found it solves problems with `savefig` where label text is cut off. A better solution may be `tight_layout`, see http://stackoverflow.com/questions/6774086/why-is-my-xlabel-cut-off-in-my-matplotlib-plot but again it seems strange you should need to in some cases. – Ed Smith Aug 18 '16 at 08:33
  • Maybe I was doing wrong, but the `plt.tight_layout()` will cut off all the legend in the saved file, the `plg.gcf().tight_layout()` the same and the `plg.gca()` doesn't have the `tight_layout()`. I agree it's pretty weird to do additional setting to include an essential part of the figure. – Kaho Chan Aug 18 '16 at 09:16

1 Answers1

8

Hope this will solve the problem.Add bbox_inches='tight' in the params which helps removing white spaces

 fig.savefig('a.jpeg', bbox_inches='tight', pad_inches=0)
vasudokala
  • 136
  • 3