0

I want to put label on plot. my code is like

import matplotlib.pyplot as plt
x1 = [1,2,3,4,5,6,7,8,9,10]
x2 = [7,3,2,4,1,4,3,5,8,4]
y  = [0,1,1,0,1,0,0,1,0,1]
plt.scatter(x1,x2,c=y)
plt.show()

Output:

plot of x1 vs x2

I want to put legend label 0 and 1 on graph. its good if label is False or true ?

It is appreciated if answer is without any iterations

GIRISH kuniyal
  • 740
  • 1
  • 5
  • 14

1 Answers1

1

In principle questions like matplotlib scatterplot with legend or Matplotlib scatter plot with legend show how to get a legend for a scatter plot.

Since you explicitely ask not to have iterations, you may of course replace iterations by mappings.

import matplotlib.pyplot as plt
import numpy as np

x1 = [1,2,3,4,5,6,7,8,9,10]
x2 = [7,3,2,4,1,4,3,5,8,4]
y  = [0,1,1,0,1,0,0,1,0,1]
plt.scatter(x1,x2,c=y, cmap="viridis")

yunique = np.unique(y).astype(float)
handles = list(map(lambda i: plt.plot([], 
                color=plt.cm.viridis(i),marker="o", ls="")[0], yunique))
labels = list(map(str, yunique.astype(bool)))
plt.legend(handles=handles, labels=labels)

plt.show()

enter image description here

Note that this is a purely academic example and it is much easier to use a for-loop.

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712