【问题标题】:matplotlib legend not working correctly with handlesmatplotlib 图例无法与句柄一起正常工作
【发布时间】:2019-06-20 18:32:35
【问题描述】:

Matplotlib 可以自动或手动显示图例,并为其提供图形句柄。但不知何故,后者对我来说不能正常工作。举个例子:

legend_handles = {}
lgh, = plt.plot([0, 1], [0, 1], '-r')
lgh, = plt.plot([0, 1], [1, 1], '-r')
legend_handles["a"] = lgh
lgh, = plt.plot([0, 1], [1, 0], '-b')
legend_handles["b"] = lgh
plt.legend(legend_handles);

这将给出一个带有两条红线的图例,而不是一条蓝线和一条红线。

如何让它只显示图例的选择?

【问题讨论】:

  • 如果你用legend_handles['a'], = plt.plot([0, 1], [1, 1], '-r')代替lgh, = plt.plot([0, 1], [1, 1], '-r')b也一样,只是忽略第一个返回值,会发生什么?我不希望有什么不同,但我不在桌面上,所以我无法检查。
  • 不应该是lgh, = plt.plot([0, 1], [1, 0], '-b')吗?否则你的蓝线与红线重叠

标签: python matplotlib


【解决方案1】:

no indication 传说将支持字典作为输入。相反,签名是

legend()                  ## (1)
legend(labels)            ## (2)
legend(handles, labels)   ## (3)

这里使用的是 (2),所以三行中,只有前 2 行用字典的键标记(因为字典只有两个键)。

如果需要用到字典,需要先解包得到两个列表,可以用来实现case(3)。

import matplotlib.pyplot as plt

legend_handles = {}
lgh1, = plt.plot([0, 1], [0, 1], '-r')
lgh2, = plt.plot([0, 1], [1, 1], '-r')
legend_handles["a"] = lgh1
lgh3, = plt.plot([1, 0], [1, 0], '-b')
legend_handles["b"] = lgh3

labels, handles = zip(*legend_handles.items())
plt.legend(handles, labels)

plt.show()

但是,根本不使用字典似乎更简单:

import matplotlib.pyplot as plt

lgh1, = plt.plot([0, 1], [0, 1], '-r')
lgh2, = plt.plot([0, 1], [1, 1], '-r')
lgh3, = plt.plot([1, 0], [1, 0], '-b')

plt.legend([lgh1, lgh3], list("ab"))

plt.show()

不要忘记,通过将label 直接提供给艺术家来创建图例的规范解决方案,

import matplotlib.pyplot as plt

lgh1, = plt.plot([0, 1], [0, 1], '-r', label="a")
lgh2, = plt.plot([0, 1], [1, 1], '-r')
lgh3, = plt.plot([1, 0], [1, 0], '-b', label="b")

plt.legend()

plt.show()

所有情况下的结果:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-15
    • 1970-01-01
    • 1970-01-01
    • 2017-12-14
    • 2020-08-19
    相关资源
    最近更新 更多