Lukáš Altman
Lukáš Altman

Reputation: 527

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

Upvotes: 1

Views: 2256

Answers (1)

nicktids
nicktids

Reputation: 173

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

Upvotes: 3

Related Questions