2

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 2

4

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. It is possible to show the legend or assign labels to colors. For example, red point is P1 and so on.
Yes you can, but I would do it a bit differently to keep it simple. I edited my answer.
3
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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.