Anil Sarode
Anil Sarode

Reputation: 301

How to add multiple legends with different markers in scatter plot in python?

This link the accepted answer explains how to plot the scatter plot for binary classification. but did not explain how to change the default color for the markers. so I write the code as given below to change the color of the marker

import matplotlib.colors as mcolors
plt.figure(num=0, figsize=(8, 6), dpi=80, facecolor='w', edgecolor='k')

x=df.iloc[:,0:1].values
y=df.iloc[:,1:2].values
z=df.iloc[:,2:3].values

l=plt.scatter(x,y, c=z,cmap = mcolors.ListedColormap(["blue", "red"]),marker='+')
plt.xlabel('Exam 1 score',fontsize=14)
plt.ylabel('Exam 2 score',fontsize=14)
# Turn on the minor TICKS, which are required for the minor GRID
plt.minorticks_on()

# Customize the major grid
plt.grid(which='major', linestyle='-', linewidth='0.5', color='black')
# Customize the minor grid

plt.grid(which='minor', linestyle=':', linewidth='0.5', color='blue')
plt.legend((l,l),("Admitted", "Not Admitted"), loc="upper right")
plt.show()  

But now I tried to add legend as plt.legend((l,l),("Admitted", "Not Admitted"), loc="upper right"),the result is as shown in the fig. For this I took help from here, they plotted multiple scatter plots but for my case, I have only one scatter plot.

enter image description here

But as shown in the above resultant figure the marker color is the same for both markers in the legend. So my question is how to add multiple legends with different marker colors or different markers by using plt.legend() in scatter plot?

Upvotes: 0

Views: 1698

Answers (1)

Diziet Asahi
Diziet Asahi

Reputation: 40667

Since matplotlib 3.1, you can use a scatter's legend_elements() to facilitate legend creation.

import matplotlib.colors as mcolors
plt.figure(num=0, figsize=(8, 6), dpi=80, facecolor='w', edgecolor='k')

x=np.random.random(size=(10,))
y=np.random.random(size=(10,))
z=np.random.choice([0,1], size=(10,))

s = plt.scatter(x,y, c=z,cmap = mcolors.ListedColormap(["blue", "red"]),marker='+')
plt.xlabel('Exam 1 score',fontsize=14)
plt.ylabel('Exam 2 score',fontsize=14)
# Turn on the minor TICKS, which are required for the minor GRID
plt.minorticks_on()

# Customize the major grid
plt.grid(which='major', linestyle='-', linewidth='0.5', color='black')
# Customize the minor grid

plt.grid(which='minor', linestyle=':', linewidth='0.5', color='blue')
h,l = s.legend_elements()
plt.legend(h,("Admitted", "Not Admitted"))

enter image description here

more examples here

Upvotes: 2

Related Questions