17

In my code I've already executed

ax.plot(x, y, 'b.-', ...)

and need to be able to set the label for the corresponding line after the fact, to have the same effect as if I'd

ax.plot(x, y, 'b.-', label='lbl', ...)

Is there a way to do this in Matplotlib?

orome
  • 45,163
  • 57
  • 202
  • 418

1 Answers1

21

If you grab the line2D object when you create it, you can set the label using line.set_label():

line, = ax.plot(x, y, 'b.-', ...)
line.set_label('line 1')

If you don't, you can find the line2D from the Axes:

ax.plot(x, y, 'b.-', ...)
ax.lines[-1].set_label('line 1')

Note, ax.lines[-1] will access the last line created, so if you make more than one line, you would need to be careful which line you set the label on using this method.


A minimal example:

import matplotlib.pyplot as plt
fig,ax = plt.subplots(1)
l,=ax.plot(range(5))
l.set_label('line 1')
ax.legend()
plt.show()

enter image description here

tmdavison
  • 64,360
  • 12
  • 187
  • 165
  • 1
    Thank you! I was using `ax.set_label` to no effect. Can you explain why `ax.set_label` does not work here? – timgeb Nov 29 '18 at 07:50
  • 1
    `ax.set_label` would set the label of the `Axes` instance, not the line. Since you can have multiple lines on an `Axes`, its not clear what the Axes label would be used for – tmdavison Nov 29 '18 at 14:15
  • After adjusting the label in a real time updated plot that is redrawn by `fig.canvas.draw()`, I needed to run `ax.legend()` to redraw the legend itself. – Andris Jul 24 '19 at 09:28
  • Are there any occasions when `l = ax.plot(...)` (i.e. *without a comma*) would return a list containing more than one `Line2D` object? – pfabri Feb 18 '21 at 15:09
  • 1
    @pfabri of course, if you plot more than one line in your `ax.plot` command – tmdavison Feb 18 '21 at 15:18