python - 图例的“最佳”位置是覆盖文本

标签 python matplotlib legend

我正在向绘图中添加一些文本(总是在左上角),当我使用 loc='best' 添加图例时,它似乎忽略了文本。

重现问题的代码:

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

我得到的结果:

enter image description here

我的文字总是在同一个地方,所以如果我可以从 best 选项中排除“左上角”,它也能正常工作。但是很好奇为什么loc的算法会忽略它。

谢谢

最佳答案

不确定人们是否仍然感兴趣,但我遇到了同样的问题,这是另一种解决方法:

您可以使用bbox_to_anchor 来限制图例的自由搜索空间。当然,要使用它,您需要提前大致知道文本的位置。

对于您的代码,将 legend 行更改为 plt.gca().legend(loc='best', bbox_to_anchor=(0, 0, 1, 0.9))(将图例限制在垂直空间的下部 90%)。

完整示例:

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

顺便说一句,我在 github 开了一个问题

关于python - 图例的“最佳”位置是覆盖文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70656115/

相关文章:

Python递归错误,但没有使用递归

python - 如何在seaborn barplot中的所有条形顶部添加数据标签?

python - 在 Python 中绘制 Networkx 图

matplotlib - 在 matplotlib 中更改图例字体大小后,如何更新图例标签间距?

r - 如何在ggplot2图例中包含黄土线?

python - 如何在图形绘图中添加键?

python - dict 中的值不允许我更改它

python - Django channel websocket.receive 未处理

由于缩进而导致 Python 打印错误

python - 在 matplotlib 子图中放大绘图