没有发现带有标签的把手放在图例中

Yeh*_*uda 26 python matplotlib legend

我正在尝试在 PyPlot 中创建一个平行四边形。我不适合绘制平行四边形——首先我要放入矢量箭头——使用以下代码:

fig = plt.figure()
ax = fig.add_subplot(111)
ax.spines['left'].set_position('zero')
ax.spines['right'].set_color('none')
ax.spines['bottom'].set_position('zero')
ax.spines['top'].set_color('none')
plt.axis([-5,5,-5,5])
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
plt.grid()
plt.arrow(0,0, 3,1, head_width=0.2, color='r', length_includes_head=True, label='u')
plt.arrow(0,0, 1,3, head_width=0.2, color='r', length_includes_head=True, label='v')
plt.arrow(0,0, 4,4, head_width=0.2, color='r', length_includes_head=True, label='u+v')
plt.legend()
Run Code Online (Sandbox Code Playgroud)

这将返回以下错误:

No handles with labels found to put in legend.
Run Code Online (Sandbox Code Playgroud)

我不确定为什么,因为根据 的文档plt.arrow()label是一个可以接受的 kwarg,并且plt.legend()表面上应该阅读它。该图的其余部分绘制得很好;它只是缺少传说。

小智 30

可能已经晚了,但对于任何有同样问题的人来说,解决方案是使用legend()相应的方法而ax不是plt

fig = plt.figure()
ax = fig.add_subplot(111)
ax.spines['left'].set_position('zero')
ax.spines['right'].set_color('none')
ax.spines['bottom'].set_position('zero')
ax.spines['top'].set_color('none')
plt.axis([-5,5,-5,5])
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
plt.grid()
plt.arrow(0,0, 3,1, head_width=0.2, color='r', length_includes_head=True, label='u')
plt.arrow(0,0, 1,3, head_width=0.2, color='r', length_includes_head=True, label='v')
plt.arrow(0,0, 4,4, head_width=0.2, color='r', length_includes_head=True, label='u+v')
ax.legend()
Run Code Online (Sandbox Code Playgroud)

  • 很容易忘记你有次要情节。谢谢你。真的帮了我大忙。 (2认同)

abc*_*abc 19

您可以明确定义图例中的元素。

为了完全控制哪些艺术家有图例条目,可以分别传递一个图例艺术家的迭代,然后分别传递一个图例标签的迭代。参考

例子:

arr1 = plt.arrow(0,0, 3,1, head_width=0.2, color='r', length_includes_head=True)
arr2 = plt.arrow(0,0, 1,3, head_width=0.2, color='g', length_includes_head=True)
arr3 = plt.arrow(0,0, 4,4, head_width=0.2, color='b', length_includes_head=True)

plt.xlim(0,5)
plt.ylim(0,5)

plt.legend([arr1, arr2, arr3], ['u','v','u+v'])
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

  • 话虽这么说,图例不应该使用“plt.arrow()”中提供的标签吗? (12认同)

小智 8

抛出错误是因为您没有指定标签文本

要么做这样的事情

plt.hist([x01, x02,x03], color=["lightcoral","lightskyblue","slategrey"], stacked=True, 
             label=['Supressed','Active','Resolved'])
plt.legend()
Run Code Online (Sandbox Code Playgroud)

或者

如果您没有指定标签文本,请不要使用plt.legend() ,如以下错误示例所示:

plt.hist([x01])
plt.legend()
Run Code Online (Sandbox Code Playgroud)

上面的代码会抛出相同的错误,因此要么删除图例函数,要么提供它需要的内容 -> 标签。旁注:这里 x01 只是我要为其创建直方图的数字列表,在第一个示例中,它们是用于创建堆积条形图的三个数字列表

最重要的是,由于未指定图例文本并调用/初始化图例,因此引发此错误


Oli*_*del 5

我在使用以下划线开头的标签时遇到此错误

plt.plot(x, y, label = '_bad_name')

从标签中删除前面的下划线解决了问题