Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'best' location for legend is covering text

I am adding some text to my plot (always in the left top corner), and when I add legend with loc='best' it seems to ignore the text.

Code to reproduce the problem:

import matplotlib.pyplot as plt
x = [1, 2]
plt.plot(x, x, label='plot name')
plt.gca().text(0.05, 0.95, 'some text', transform=plt.gca().transAxes, verticalalignment='top')
plt.legend(loc='best')
plt.show()

The result I get:

enter image description here

My text is always in the same place, so if I can exclude 'upper left' from best options it will work as well. But curious why the algorithm of loc ignores it.

Thanks

like image 342
Shaq Avatar asked Oct 16 '25 04:10

Shaq


1 Answers

Not sure if people still interested, but I encountered the same here is another work around:

You can use the bbox_to_anchor to limit the legend's free searching space. Of course to use that you need to know roughly where your text will be in advance.

For your code, change the legend line to plt.gca().legend(loc='best', bbox_to_anchor=(0, 0, 1, 0.9)) (limit the legend to only the lower 90% of the vertical space).

Full example:

import matplotlib.pyplot as plt
x = [1, 2]
plt.plot(x, x, label='plot name')
plt.gca().text(0.05, 0.95, 'some text', transform=plt.gca().transAxes, verticalalignment='top')
plt.gca().legend(loc='best',  bbox_to_anchor=(0, 0, 1, 0.9))
plt.show()

BTW, I opened an issue at github

like image 102
ym3141 Avatar answered Oct 17 '25 17:10

ym3141