If you capture 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 do not, you can find line2D from Axes :
ax.plot(x, y, 'b.-', ...) ax.lines[-1].set_label('line 1')
Note. ax.lines[-1] will have access to the last line created, so if you create multiple lines, you need to be careful which line you set for the label using this method.
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()

source share