How to label a line in matplotlib (python)?

Question:

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?

Asked By: Sibbs Gambling

||

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

Answered By: shaunakde

when adding the label attribute, don’t forget to add .legend() method.

import matplotlib.pyplot as plt
plt.plot([1,2],[3,5],'ro',label='one')
plt.plot([1,2],[1,2],'g^',label='two')
plt.plot([1,2],[1,6],'bs',label='three')
plt.axis([0,4,0,10])
plt.ylabel('x2')
plt.xlabel('x1')
plt.legend()
plt.show()

enter image description here

Answered By: Ahmed Bargady

This should work :

plt.legend(YourDataFrame.columns)
Answered By: Sergey
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.