1

I am having a hard time trying to create a scatter plot that will show points of different classes with different colors and the corresponding label of the class in the legend.

I have 52 samples, 2 features and 3 classes(class 1,2 and 3). The data are in X array and the labels in labels array.

I want to plot the legend that will contain the class names (1,2 and 3) for the corresponding colors.


My code:

import numpy as np
import matplotlib.pyplot as plt

x = np.random.rand(52,2)

labels = np.ones(x.shape[0])
labels[0:8] = 1
labels[8:31] = 2 
labels[31:] = 3

plt.scatter(x[:,0], x[:,1], c = labels, label = labels)
plt.legend()
plt.show()

Result:

enter image description here

seralouk
  • 30,938
  • 9
  • 118
  • 133

2 Answers2

3

One way to do this would be to plot your classes separately:

x = np.random.rand(52,2)

labels = np.ones(x.shape[0])
labels[0:8] = 1
labels[8:31] = 2 
labels[31:] = 3


for i in np.unique(labels):
    plt.scatter(x[np.where(labels==i),0], x[np.where(labels==i),1], label=i)
plt.legend()
plt.show()

enter image description here

sacuL
  • 49,704
  • 8
  • 81
  • 106
  • Hello. I am coming back with a new question. Can i do the same but this time using seaborn's sns.jointplot function ? – seralouk Jul 06 '18 at 12:27
0

Taken from: https://matplotlib.org/api/_as_gen/matplotlib.pyplot.legend.html

3. Explicitly defining the elements in the legend

For full control of which artists have a legend entry, it is possible to pass an iterable of legend artists followed by an iterable of legend labels respectively:

legend((line1, line2, line3), ('label1', 'label2', 'label3'))
sciroccorics
  • 2,357
  • 1
  • 8
  • 21