How to set a label for an already constructed line in matplotlib?

In my code I already executed

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

and you need to be able to set the label for the corresponding line after the fact in order to have the same effect as me

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

Is there a way to do this in matplotlib?

+5
source share
1 answer

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

enter image description here

+6
source

Source: https://habr.com/ru/post/1247128/


All Articles