简体   繁体   中英

Legend - get label

I get this error, what is wrong please?

plt.legend(handles=[d1, d2])
  File "/usr/lib/python3/dist-packages/matplotlib/pyplot.py", line 3553, in legend
    ret = gca().legend(*args, **kwargs)
  File "/usr/lib/python3/dist-packages/matplotlib/axes/_axes.py", line 501, in legend
    labels = [handle.get_label() for handle in handles]
  File "/usr/lib/python3/dist-packages/matplotlib/axes/_axes.py", line 501, in <listcomp>
    labels = [handle.get_label() for handle in handles]
AttributeError: 'list' object has no attribute 'get_label'

The part of code is

d1 = plt.plot(xdata, ydata1, "sb", markersize = 5, ls = "solid", label = 'name1', linestyle = 'dashed')
d2 = plt.plot(xdata, ydata2, "vr", markersize = 5, ls = "solid", label = 'name2', linestyle = 'dashed')

plt.legend(handles=[d1, d2])

Try adding a comma as per the docs
https://matplotlib.org/tutorials/intermediate/legend_guide.html#legend-handlers

d1, = plt.plot(xdata, ydata1, "sb", markersize = 5, ls = "solid", label = 'name1', linestyle = 'dashed')
d2, = plt.plot(xdata, ydata2, "vr", markersize = 5, ls = "solid", label = 'name2', linestyle = 'dashed')

plt.legend(handles=[d1, d2])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM