0

I am trying to coordinate the positions of ax.legend() and ax.text(), but it looks like option loc = 'best' is not that smart

legend

clearly the legend is blocking the text, I know I can use loc = 'lower left' instead, but I am just curious, why does legend not care about text?

Here is the code

import numpy
  
## matplotlib
import matplotlib
matplotlib.use('Agg')
import pylab
from  matplotlib import rc
rc('font', **{'family': 'sans-serif', 'sans-serif': ['Times-Roman']})
rc('text', usetex = True)
matplotlib.rcParams['text.latex.preamble'] = [r"\usepackage{amsmath}"]

def test_plot():
    n_columns, n_rows = 1, 1
    pylab.figure(figsize = (n_columns * 2.5, n_rows * 2.0))
    axs = {}
    xs = numpy.linspace(0.0001, 2.0 * numpy.pi, 100)

    ax = pylab.subplot(n_rows, n_columns, 1)
    axs[1] = ax
    ys = numpy.sin(xs) / xs
    ax.plot(xs, ys, label = r'$1$')
    ax.text(0.8, 0.8, r'$\frac{\sin{x}}{x}$', transform = ax.transAxes)
    ax.legend(loc = 'best', frameon = 0)

    pylab.tight_layout()
    pylab.savefig('./test.png', dpi = 2000)
    return

if __name__ == '__main__':
    test_plot()

Thanks in advance!

zyy
  • 1,271
  • 15
  • 25
  • 1
    Does this answer your question? [How to put the legend out of the plot](https://stackoverflow.com/questions/4700614/how-to-put-the-legend-out-of-the-plot) – Trenton McKinney Aug 18 '20 at 21:10
  • `best` should try to avoid text artists if they are child artists of the same axes as the legend. – Jody Klymak Aug 18 '20 at 22:53
  • ... or if you for some reason are not getting best to avoid that corner (say the text was placed as figure artists) you could put a patch up there that was the same color as the axes facecolor and then the legend would try and avoid that. – Jody Klymak Aug 18 '20 at 22:55
  • @JodyKlymak The texts were added like `ax.text(0.1, 0.8, 'text', transform = ax.transAxes)` for each subplots, and legends did not try to avoid it. – zyy Aug 18 '20 at 23:04
  • Can you provide a complete minimal reproducible example? – Jody Klymak Aug 19 '20 at 03:15
  • @JodyKlymak I just updated with an example and figure. In the first subplot, the legend is trying to avoid the plots but not the text. – zyy Aug 19 '20 at 04:26

1 Answers1

1

So you want to put legend anywhere but the upper left...? You could always just use:

plt.legend(loc="upper right")  

Or "left", "lower left", "center", "upper center", "lower center", "right", or "lower right"

Or if you want it to chose a random spot while avoiding "upper left":

import random

spot = ["center", "upper center", "lower center", "right", "upper right", 
"lower right", "left", "lower left"]
random_spot = spot[random.randint(0, spot.__len__() - 1)]
plt.legend(loc=random_spot, borderaxespad=1)

This should place it anywhere randomly, exept the upper left corner. It this what you need?

Three Point 14
  • 150
  • 2
  • 8