Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set label for an already plotted line in matplotlib?

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?

like image 914
orome Avatar asked Apr 14 '16 13:04

orome


People also ask

How do I label a specific point in Matplotlib?

To label the scatter plot points in Matplotlib, we can use the matplotlib. pyplot. annotate() function, which adds a string at the specified position.

How do I show values on a line graph in Matplotlib?

Just call the plot() function and provide your x and y values. Calling the show() function outputs the plot visually.

How do you make a legend outside a plot in Python?

In Matplotlib, to set a legend outside of a plot you have to use the legend() method and pass the bbox_to_anchor attribute to it. We use the bbox_to_anchor=(x,y) attribute. Here x and y specify the coordinates of the legend.


1 Answers

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

like image 116
tmdavison Avatar answered Sep 28 '22 05:09

tmdavison