Skip to main content
 首页 » 编程设计

Python 散点图 : Changing color based on both X and Y values

2024年12月31日9tuyile006

我尝试使用 cmap 以及 if/else 语句重新创建附加的图像。

我目前的尝试是基于 this thread 中给出的建议

我尝试使用 1.8<=x<=2.2 但出现错误。

下面是我当前的代码:

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() 

请您参考如下方法:

要绘制该图,您需要传递一个包含每个点颜色的数组。在这种情况下,颜色是到点 (2, 2) 的距离,因为分布以该点为中心。

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()