将图例与轴对齐

时间:2019-08-15 09:18:50

标签: matplotlib legend

对我来说,经常出现的烦恼是试图用轴来装饰matplotlib图例。通常建议将其放置在图的右上角

plt.legend(bbox_to_anchor=(1.04, 1), loc="upper left")

喜欢

import numpy
import matplotlib.pyplot as plt


x = numpy.linspace(-2, 2, 100)
y = x ** 2
plt.plot(x, y, "-", label="x**2")

plt.legend(bbox_to_anchor=(1.04, 1), loc="upper left")
plt.grid()
# plt.show()
plt.savefig("out.png", transparent=True)

尽管如此,这还是有差距的

enter image description here

摆弄诸如bbox_to_anchor=(1.04, 1.015)之类的魔术值的确会上下移动图例,但是如果您在一千次尝试后终于正确理解了图例,则在调整图的大小后都将其弄乱了。

关于如何做得更好的任何提示?

1 个答案:

答案 0 :(得分:1)

您可以在指定borderaxespad=0的同时使用legend获得所需的对齐方式。


完整代码

import numpy
import matplotlib.pyplot as plt

x = numpy.linspace(-2, 2, 100)
y = x ** 2
plt.plot(x, y, "-", label="x**2")

plt.legend(bbox_to_anchor=(1.04, 1), borderaxespad=0) # <--- Here
plt.grid()

enter image description here

相关问题