Python图例属性错误 [英] Python legend attribute error
问题描述
为什么我在这里遇到与plt.plot标签有关的错误?
Why am I getting an error here that relates to the plt.plot label?
fig = plt.figure()
ax = plt.gca()
barplt = plt.bar(bins,frq,align='center',label='Dgr')
normplt = plt.plot(bins_n,frq_n,'--r', label='Norm');
ax.set_xlim([min(bins)-1, max(bins)+1])
ax.set_ylim([0, max(frq)])
plt.xlabel('Dgr')
plt.ylabel('Frequency')
plt.show()
plt.legend(handles=[barplt,normplt])
这是我得到的错误: 列表"对象没有属性"get_label"
This is the error that I get: 'list' object has no attribute 'get_label'
推荐答案
因为plt.plot
可以一次绘制多条线,所以即使您仅绘制一条线(例如,在您的情况,长度为1)的列表.抓住图例的句柄时,您只想使用此列表的第一项(实际的line2D
对象).
Because plt.plot
can plot more than one line at once, it returns a list of line2D
objects, even if you only plot one line (i.e. in your case, a list of length 1). When you grab its handle for the legend, you want to only use the first item of this list (the actual line2D
object).
(至少)有两种方法可以解决此问题:
There are (at least) two ways you can resolve this:
1)调用plt.plot
时,在normplt
之后添加逗号,以便仅将列表中的第一项存储在normplt
1) add a comma after normplt
when you call plt.plot
, to only store the first item from the list in normplt
barplt = plt.bar(bins,frq,width,align='center',label='Dgr')
normplt, = plt.plot(bins_n,frq_n,'--r', label='Norm') # note the comma after normplt
print normplt
# Line2D(Norm) <-- This is the line2D object, not a list, so we can use it in legend
...
plt.legend(handles=[barplt,normplt])
2)调用plt.legend
(normplt[0]
)时,仅使用列表中的第一项:
2) Use only the first item in the list when you call plt.legend
(normplt[0]
):
barplt = plt.bar(bins,frq,width,align='center',label='Dgr')
normplt = plt.plot(bins_n,frq_n,'--r', label='Norm')
print normplt
# [<matplotlib.lines.Line2D object at 0x112076710>]
# Note, this is a list containing the Line2D object. We just want the object,
# so we can use normplt[0] in legend
...
plt.legend(handles=[barplt,normplt[0]])
这篇关于Python图例属性错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!