Reputation: 1574
I am trying to coordinate the positions of ax.legend()
and ax.text()
, but it looks like option loc = 'best'
is not that smart
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!
Upvotes: 0
Views: 389
Reputation: 150
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?
Upvotes: 1