【问题标题】:Why does legend block text in matplotlib?为什么图例会阻止 matplotlib 中的文本?
【发布时间】:2020-08-18 21:01:38
【问题描述】:

我正在尝试协调ax.legend()ax.text() 的位置,但看起来选项loc = 'best' 并不那么聪明

明明是legend挡住了文字,我知道可以改用loc = 'lower left',但是我很好奇,为什么legend不关心文字?

这里是代码

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()

提前致谢!

【问题讨论】:

  • 这能回答你的问题吗? How to put the legend out of the plot
  • best 应该尽量避免文本艺术家,如果他们是与图例相同轴的子艺术家。
  • ... 或者如果你因为某种原因没有最好地避开那个角落(比如文本被放置为图形艺术家),你可以在那里放置一个与轴颜色相同的补丁facecolor,然后图例会尝试避免这种情况。
  • @JodyKlymak 为每个子图添加了类似ax.text(0.1, 0.8, 'text', transform = ax.transAxes)的文本,图例并没有试图避免它。
  • 您能提供一个完整的最小可重现示例吗?

标签: python matplotlib location legend


【解决方案1】:

所以你想把图例放在左上角以外的任何地方......?你总是可以使用:

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)

这应该将它随机放置在任何位置,除了左上角。这是你需要的吗?

【讨论】:

  • 对不起,我希望它自动选择,但只是避免upper left
  • 抱歉,为了更清楚,我重新表述了这个问题......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-07-19
  • 1970-01-01
  • 2011-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多