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!
Plotting from an IPython shell draw() . Using plt. show() in Matplotlib mode is not required.
show() and plt. draw() are unnecessary and / or blocking in one way or the other.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With