Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to label a line in matplotlib (python)?

Tags:

I followed the documentation but still failed to label a line.

plt.plot([min(np.array(positions)[:,0]), max(np.array(positions)[:,0])], [0,0], color='k', label='East') # West-East
plt.plot([0,0], [min(np.array(positions)[:,1]), max(np.array(positions)[:,1])], color='k', label='North') # South-North

In the code snippet above, I am trying to plot out the North direction and the East direction.

position contains the points to be plotted.

But I end up with 2 straight lines with NO labels as follows: enter image description here

Where went wrong?

like image 733
Sibbs Gambling Avatar asked Jul 30 '13 07:07

Sibbs Gambling


People also ask

How do I plot a line in matplotlib?

To plot a line plot in Matplotlib, you use the generic plot() function from the PyPlot instance. There's no specific lineplot() function - the generic one automatically plots using lines or markers. This results in much the same line plot as before, as the values of x are inferred.


1 Answers

The argument label is used to set the string that will be shown in the legend. For example consider the following snippet:

  import matplotlib.pyplot as plt
  plt.plot([1,2,3],'r-',label='Sample Label Red')
  plt.plot([0.5,2,3.5],'b-',label='Sample Label Blue')
  plt.legend()
  plt.show()

This will plot 2 lines as shown: Plot With 2 lines

The arrow function supports labels. Do check this link: http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.arrow

like image 147
shaunakde Avatar answered Oct 04 '22 22:10

shaunakde