[英]Why does legend block text in matplotlib?
我正在尝试协调ax.legend()
和ax.text()
的位置,但看起来 option loc = 'best'
并不那么聪明
显然图例阻止了文本,我知道我可以使用loc = 'lower left'
代替,但我只是好奇,为什么图例不关心文本?
这是代码
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()
提前致谢!
所以你想把图例放在左上角以外的任何地方......? 你总是可以只使用:
plt.legend(loc="upper right")
或“左”、“左下”、“中”、“中上”、“中下”、“右”或“右下”
或者,如果您希望它选择一个随机点,同时避免“左上角”:
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)
这应该将它随机放置在任何地方,除了左上角。 这是你需要的吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.