Search code examples
pythonmatplotliblegendlegend-properties

How do I assign multiple legend labels at once?


I have the following dataset:

x = [0, 1, 2, 3, 4]
y = [ [0, 1, 2, 3, 4],
      [5, 6, 7, 8, 9],
      [9, 8, 7, 6, 5] ]

Now I plot it with:

import matplotlib.pyplot as plt
plt.plot(x, y)

However, I want to label the 3 y-datasets with this command, which raises an error when .legend() is called:

lineObjects = plt.plot(x, y, label=['foo', 'bar', 'baz'])
plt.legend()

File "./plot_nmos.py", line 33, in <module>
  plt.legend()
...
AttributeError: 'list' object has no attribute 'startswith'

When I inspect the lineObjects:

>>> lineObjects[0].get_label()
['foo', 'bar', 'baz']
>>> lineObjects[1].get_label()
['foo', 'bar', 'baz']
>>> lineObjects[2].get_label()
['foo', 'bar', 'baz']

Question

Is there an elegant way to assign multiple labels by just using the .plot() method?


Solution

  • It is not possible to plot those two arrays agains each other directly (with at least version 1.1.1), therefore you must be looping over your y arrays. My advice would be to loop over the labels at the same time:

    import matplotlib.pyplot as plt
    
    x = [0, 1, 2, 3, 4]
    y = [ [0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [9, 8, 7, 6, 5] ]
    labels = ['foo', 'bar', 'baz']
    
    for y_arr, label in zip(y, labels):
        plt.plot(x, y_arr, label=label)
    
    plt.legend()
    plt.show()
    

    Edit: @gcalmettes pointed out that as numpy arrays, it is possible to plot all the lines at the same time (by transposing them). See @gcalmettes answer & comments for details.