使用python绘制散点密度图(散点图并标示密度)
原文链接:
最初遇到这个问题的时候,找到的大答案是绘制contour图,比如:
这当然很漂亮,但是这需要有三列数字来标示一个平面;但其实我的问题是仅有两列数的时候如何标示密度:
方法一,使用hist2d:
from matplotlib.colors import LogNorm from pylab import * #normal distribution center at x=0 and y=5 x = randn(100000) y = randn(100000)+5 hist2d(x, y, bins=40, norm=LogNorm()) colorbar() show()
方法二,使用hexbin
参见这个例子:
方法三,使用gaussian_kde
关于gaussian_kde的介绍可以参见这里:, 简而言之,这是使用Kernel density estimation的方法,估计出每个位置的密度值。
import numpy as np import matplotlib.pyplot as plt from scipy.stats import gaussian_kde # Generate fake data x = np.random.normal(size=1000) y = x *3+ np.random.normal(size=1000) # Calculate the point density xy = np.vstack([x,y]) z = gaussian_kde(xy)(xy) fig, ax = plt.subplots() ax.scatter(x, y, c=z, s=100, edgecolor=) plt.show()