legend goes outside of the window area

Question:

As you can see in the picture below, the legend with its box goes outside of the figure area on the horizontal line.

enter image description here

Note that I cropped the upper part since the problem is with the width.

The matplot script is rather lengthy and most of the code is not relevant to this question. In short, I have

 fig = plt.figure(1,figsize=(10.67,6.6))
 ...
 leg1 = plt.legend(handles = marker_handles,bbox_to_anchor=(1.2,1),loc='upper right', ncol=1)
 ax.add_artist(leg1)
 ...
 plt.savefig(filename+'.png')
 plt.show()

If I increase the figsize, then plt.show() shows a very big window and still the legend goes beyond the window border.

How can I fix that?

Asked By: mahmood

||

Answers:

either use

plt.tight_layout() to automatically adjust the dimensions of the Axes to accomodate the legend box

or, if you prefer more fine control:

plt.subplots_adjust(right=xxxx) to shrink the width of the Axes to accomodate the legend box

Answered By: Diziet Asahi
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.