'How to prevent matplotlib figure is resized due to outside legend

I got a general issue with a plotting function using matplotlib.pyplot. I plot a set of stacked horizontal bar charts, the goal is to produce congruent figures, the embedded grid is suppose to fit, but the image gets resized, when I change the input data. However, if i plot the image without the legend, I receive the desired output. But I do want to include a legend of course ! The formatting lines I include are the following:

figure size

fig,ax = plt.subplots(1,figsize=(20,9))

grid definition

plt.grid(color="darkgrey")

legend defintion

ax.legend([handles[i] for i in order], [labels[i] for i in order],
              bbox_to_anchor=((0.5, -0.15)), loc="upper center",fontsize="medium",ncol=5)

tight layout

fig.tight_layout()

store the image

fig.savefig(str(figname)+'.jpg',bbox_inches='tight',quality=95,dpi=300)


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source