The Python Oracle

Adding a legend to PyPlot in Matplotlib in the simplest manner possible

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Track title: CC H Dvoks String Quartet No 12 Ame

--

Chapters
00:00 Question
01:44 Accepted answer (Score 767)
02:20 Answer 2 (Score 61)
03:13 Answer 3 (Score 26)
03:41 Answer 4 (Score 20)
03:58 Thank you

--

Full question
https://stackoverflow.com/questions/1912...

Question links:
[from the official site]: http://matplotlib.org/users/legend_guide...

Accepted answer links:
[plot()]: http://matplotlib.org/api/pyplot_api.htm...
[legend(loc='upper left')]: http://matplotlib.org/api/pyplot_api.htm...
[image]: https://i.stack.imgur.com/GyMXH.png
http://jakevdp.github.io/mpl_tutorial/tu...

Answer 2 links:
[image]: https://i.stack.imgur.com/GQEYM.png

Answer 3 links:
[image]: https://i.stack.imgur.com/jPnzz.png

Answer 4 links:
[documentation]: https://matplotlib.org/3.1.1/gallery/tex...
[image]: https://i.stack.imgur.com/ChnWQ.png

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #matplotlib #plot

#avk47



ACCEPTED ANSWER

Score 843


Add a label= to each of your plot() calls, and then call legend(loc='upper left').

Consider this sample (tested with Python 3.8.0):

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 20, 1000)
y1 = np.sin(x)
y2 = np.cos(x)

plt.plot(x, y1, "-b", label="sine")
plt.plot(x, y2, "-r", label="cosine")
plt.legend(loc="upper left")
plt.ylim(-1.5, 2.0)
plt.show()

enter image description here Slightly modified from this tutorial: http://jakevdp.github.io/mpl_tutorial/tutorial_pages/tut1.html




ANSWER 2

Score 63


You can access the Axes instance (ax) with plt.gca(). In this case, you can use

plt.gca().legend()

You can do this either by using the label= keyword in each of your plt.plot() calls or by assigning your labels as a tuple or list within legend, as in this working example:

import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-0.75,1,100)
y0 = np.exp(2 + 3*x - 7*x**3)
y1 = 7-4*np.sin(4*x)
plt.plot(x,y0,x,y1)
plt.gca().legend(('y0','y1'))
plt.show()

pltGcaLegend

However, if you need to access the Axes instance more that once, I do recommend saving it to the variable ax with

ax = plt.gca()

and then calling ax instead of plt.gca().




ANSWER 3

Score 28


Here's an example to help you out ...

fig = plt.figure(figsize=(10,5))
ax = fig.add_subplot(111)
ax.set_title('ADR vs Rating (CS:GO)')
ax.scatter(x=data[:,0],y=data[:,1],label='Data')
plt.plot(data[:,0], m*data[:,0] + b,color='red',label='Our Fitting 
Line')
ax.set_xlabel('ADR')
ax.set_ylabel('Rating')
ax.legend(loc='best')
plt.show()

enter image description here




ANSWER 4

Score 15


A simple plot for sine and cosine curves with a legend.

Used matplotlib.pyplot

import math
import matplotlib.pyplot as plt
x=[]
for i in range(-314,314):
    x.append(i/100)
ysin=[math.sin(i) for i in x]
ycos=[math.cos(i) for i in x]
plt.plot(x,ysin,label='sin(x)')  #specify label for the corresponding curve
plt.plot(x,ycos,label='cos(x)')
plt.xticks([-3.14,-1.57,0,1.57,3.14],['-$\pi$','-$\pi$/2',0,'$\pi$/2','$\pi$'])
plt.legend()
plt.show()

Sin and Cosine plots (click to view image)