Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Scatterplot: Changing color based on both X and Y values

I've tried to recreate the image attached using cmaps as well as with if/else statements.

Example

My current attempt is based upon the advice given in this thread

I tried using 1.8<=x<=2.2 but I get an error.

Here is my current code below:

import numpy as np
import matplotlib.pyplot as plt
N = 500
# center, variation, number of points
x = np.random.normal(2,0.2,N)
y = np.random.normal(2,0.2,N)
colors = np.where(x<=2.2,'r',np.where(y<=2.2,'b','b'))
plt.scatter(x , y, c=colors)
plt.colorbar()
plt.show()
like image 867
Haribon66 Avatar asked Mar 15 '26 09:03

Haribon66


1 Answers

To make that plot, you need to pass an array with the color of each point. In this case the color is the distance to the point (2, 2), since the distributions are centered on that point.

import numpy as np
import matplotlib.pyplot as plt

N = 500
# center, variation, number of points
x = np.random.normal(2,0.2,N)
y = np.random.normal(2,0.2,N)

# we calculate the distance to (2, 2).
# This we are going to use to give it the color.
color = np.sqrt((x-2)**2 + (y-2)**2)

plt.scatter(x , y, c=color, cmap='plasma', alpha=0.7)
# we set a alpha
# it is what gives the transparency to the points.
# if they suppose themselves, the colors are added.

plt.show()

plot

like image 170
Lucas Avatar answered Mar 17 '26 00:03

Lucas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!