import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import gaussian_kde
# Generate fake data
N=1000
x = np.random.normal(size=N)
y = x * 3 + np.random.normal(size=N)
# Calculate the point density
xy = np.vstack([x,y]) # 将两个维度的数据叠加
z = gaussian_kde(xy)(xy) # 建立概率密度分布,并计算每个样本点的概率密度
# Sort the points by density, so that the densest points are plotted last
idx = z.argsort()
x, y, z = x[idx], y[idx], z[idx]
fig, ax = plt.subplots()
plt.scatter(x, y,c=z, s=20,cmap='Spectral') # c表示标记的颜色
plt.colorbar()
plt.show()