Using color with np.array

Viewed 259

I have the following x,y scatter points with numpy

a = np.array([
[5.033,-3.066],
[5.454,-3.492],
[-1.971,0.384],
],)
x, y = a.T
plt.scatter(x, y)
plt.ylabel('Yv')
plt.show()

And I would like to draw points with color. I mean, something like this:

a = np.array([
[5.033,-3.066] and color="black",
[5.454,-3.492] and color="black",
[-1.971,0.384] and color="red",
],)

How can I do that? I see a colormap discussed here, but don't know if that really fits my need.

2 Answers

Adding colors

Simply create a list of colors corresponding to each of your inner lists, then give it to the parameter color of the scatter method :

colors = ["black", "black", "red"]
plt.scatter(x, y, color=colors)

Result :

scatter plot with colored markers

You can use strings to specify the colors you want. The available color strings are all HTML color names (in any upper or lower case). Check them all here: HTML colors

You can also give hexadecimal RGB values like this (example for pink):

'#FFB6C1'

... or as a tuple or list of RGB values ranged from 0 to 1, like this (still for pink):

[1.0, 0.75, 0.8]

Source: Matplotlib Colors Documentation

Adding legends:

The simplest way is to scatter iteratively by row:

a = np.array([
[5.033,-3.066],
[5.454,-3.492],
[-1.971,0.384],
],)
x, y = a.T

# Creating colors and class names beforehand.
colors = ["black", "black", "red"]
classes = ["class1", "class2","class3"]
# Calling scatter per row, to differentiate each class
for x_per_class, y_per_class, color, label in zip(x, y, colors, classes):
    plt.scatter(x=x_per_class, y=y_per_class, color=color, label=label)

# Adding legends
plt.legend()

plt.ylabel('Yv')
plt.show()

Result with legend:

color scatter plot with legend

colors = ['black', 'black', 'red']
a = np.array([
[5.033,-3.066],
[5.454,-3.492],
[-1.971,0.384],
],)
x, y = a.T
print(x, y)
plt.scatter(x, y, c=colors)

plt.ylabel('Yv')
plt.show()
Related