Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
735 views
in Technique[技术] by (71.8m points)

matplotlib - Python legend attribute error

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

This is the error that I get: 'list' object has no attribute 'get_label'

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...