赞
踩
最初遇到这个问题的时候,找到的大答案是绘制contour图,比如:
http://stackoverflow.com/questions/24119920/how-to-plot-a-density-map-in-python?rq=1
这当然很漂亮,但是这需要有三列数字来标示一个平面;但其实我的问题是仅有两列数的时候如何标示密度:
方法一,使用hist2d:
例子来源: http://matplotlib.org/examples/pylab_examples/hist2d_log_demo.html
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
参见这个例子: http://matplotlib.org/examples/pylab_examples/hexbin_demo.html
方法三,使用gaussian_kde
关于gaussian_kde的介绍可以参见这里: http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.gaussian_kde.html, 简而言之,这是使用 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()
案例来源:http://stackoverflow.com/questions/20105364/how-can-i-make-a-scatter-plot-colored-by-density-in-matplotlib
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。