Mat*_*hew 7 python plot numpy matplotlib
我正在使用pyplot从python中的数千个点制作散点图.我的问题是他们倾向于集中在一个地方,而这只是一大堆积分.
是否有某种功能可以使pyplot绘图点达到某个临界密度,然后使其成为等高线图?
我的问题类似于这个问题,其中示例图具有轮廓线,其中颜色代表绘制点的密度.
谢谢
首先,您需要对数据进行密度估算.根据您选择的方法,可以获得不同的结果.
假设你想要进行高斯密度估计,根据例子scipy.stats.gaussian_kde,你可以得到密度高度:
def density_estimation(m1, m2):
X, Y = np.mgrid[xmin:xmax:100j, ymin:ymax:100j]
positions = np.vstack([X.ravel(), Y.ravel()])
values = np.vstack([m1, m2])
kernel = stats.gaussian_kde(values)
Z = np.reshape(kernel(positions).T, X.shape)
return X, Y, Z
Run Code Online (Sandbox Code Playgroud)
然后,你可以用它绘制contour与
X, Y, Z = density_estimation(m1, m2)
fig, ax = plt.subplots()
# Show density
ax.imshow(np.rot90(Z), cmap=plt.cm.gist_earth_r,
extent=[xmin, xmax, ymin, ymax])
# Add contour lines
plt.contour(X, Y, Z)
ax.plot(m1, m2, 'k.', markersize=2)
ax.set_xlim([xmin, xmax])
ax.set_ylim([ymin, ymax])
plt.show()
Run Code Online (Sandbox Code Playgroud)
作为替代方案,你可以改变基于它们的密度如图所示,标识的颜色在这里.