Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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(). 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!

like image 615
Kaho Chan Avatar asked Aug 18 '16 08:08

Kaho Chan


People also ask

Is PLT show () necessary?

Plotting from an IPython shell draw() . Using plt. show() in Matplotlib mode is not required.

Is PLT show () blocking?

show() and plt. draw() are unnecessary and / or blocking in one way or the other.

How do I save my show on PLT?

Matplotlib plots can be saved as image files using the plt. savefig() function. The plt. savefig() function needs to be called right above the plt.


1 Answers

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)
like image 194
vasudokala Avatar answered Nov 01 '22 13:11

vasudokala