FooBar
FooBar

Reputation: 16528

Matplotlib: Intelligent figure scale / legend location

Some code gives me the following matplotlib figure:

standard output

Unfortunately, the figure size is fixed and hence on the top right, the legend and the lines overlap. Is there any way to have the legend not stack on top of the lines?

I am aware that legend allows ax2.legend(loc=0), where 0 will put it into the "best" location. However, with two y axis as here, this will stack both legends on top of each other - not really the best allocation.

My next best try would be to "scale up" the figure, as manually done with an interactive graph, where I have only scaled up both axis:

scaled figure

Doing this with the "real" figure scale requires iterated "trying numbers and checking how far it goes" procedure - which may need to be redone if the graph changes. Is there any way of having matplotlib compute the scale "intelligently"?

Upvotes: 1

Views: 1394

Answers (1)

MartinsM
MartinsM

Reputation: 110

If the best location plt.legend(loc='best') fails, try putting the legend outside of the plot:

plt.legend(loc='upper left', bbox_to_anchor=(1.02, 1), borderaxespad=0)

You can scale only legend, not the whole plot. Link here

More on legends here and also here.

Upvotes: 1

Related Questions