2

There are several way to make a legend with matplotlib. May be the simpler way could be:

>>> line_up, = plt.plot([1,2,3], label='Up')
>>> line_down, = plt.plot([3,2,1], label='Down')
>>> plt.legend()
<matplotlib.legend.Legend object at 0x7f527f10ca58>
>>> plt.show()

One other way could be:

>>> line_up, = plt.plot([1,2,3])
>>> line_down, = plt.plot([3,2,1])
>>> plt.legend((line_up, line_down), ('Up', 'Down'))
<matplotlib.legend.Legend object at 0x7f527eea92e8>
>>> plt.show()

This last way seems to work only with objects supporting iteration:

>>> line_up, = plt.plot([1,2,3])
>>> plt.legend((line_up), ('Up'))
/usr/lib64/python3.4/site-packages/matplotlib/cbook.py:137: MatplotlibDeprecationWarning: The "loc" positional argument to legend is deprecated. Please use the "loc" keyword instead.
  warnings.warn(message, mplDeprecation, stacklevel=1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python3.4/site-packages/matplotlib/pyplot.py", line 3519, in legend
    ret = gca().legend(*args, **kwargs)
  File "/usr/lib64/python3.4/site-packages/matplotlib/axes/_axes.py", line 496, in legend
    in zip(self._get_legend_handles(handlers), labels)]
TypeError: zip argument #2 must support iteration

If I want use absolutely the second way with only one curve ... Hown can I do ?

1 Answer 1

5

I believe the reason for this is to define a one item tuple, you would use the syntax (line_up,). Note the trailing comma.

import matplotlib.pyplot as plt
line_up, = plt.plot([1,2,3])
plt.legend((line_up,), ('Up',))
plt.show()

You could also use a list if you would rather not include the trailing comma. For example:

import matplotlib.pyplot as plt
line_up, = plt.plot([1,2,3], label='my graph')
plt.legend(handles=[line_up])
plt.show()
1
  • Oh great !!! Thanks a lot it is exactly what I looked for ! I'm ashamed that I did not find by myself ... :-((
    – servoz
    Apr 11, 2017 at 12:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.