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!