2013-06-21 41 views
4

假设我想建立在某个bin范围nbin上平滑的粒子数据的直方图。现在我有5个不同质量的粒子数据集(每组x,y有不同的质量)。通常情况下,颗粒归仓的直方图是一个简单的例子(使用numpy的):使用不同的权重创建堆积的2D直方图

heatmap, xedges, yedges = np.histogram2d(x, y, bins=nbin) 
extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]] 
heatmap = np.flipud(np.rot90(heatmap)) 
ax.imshow(heatmap, extent=extent) 

但是,如果我想补充下很多的粒子,它们有不同的质量,因此密度会有所不同。有没有办法通过一些常数来加权直方图,使得绘制的热图将成为密度的真实表示,而不仅仅是粒子总数的装仓?

我知道'权重'是一个特征,但是它只是设置权重= m_i的情况,其中m_i是每个数据集1-5的粒子质量?

+0

是的,这应该几乎做的伎俩。 – Jaime

回答

4

weights参数需要一个与xy相同长度的数组。 np.histogram2d。它不会播出一个恒定值,所以即使质量是每个通话同样以np.histogram2d,你仍然必须使用类似

weights=np.ones_like(x)*mass 

现在,你可能会遇到,如果你使用bin=nbin一个问题是,根据您传递给np.histogram2dxy的值,可能会改变分区边缘,xedges,yedges。如果你天真地将热点图加在一起,最终的结果会在错误的地方累积粒子密度。

因此,如果您想多次调用np.histogram2d并将部分热图集合在一起,则必须事先确定要在哪里进行料仓边缘。

例如:

import numpy as np 
import itertools as IT 
import matplotlib.pyplot as plt 
N = 50 
nbin = 10 

xs = [np.array([i,i,i+1,i+1]) for i in range(N)] 
ys = [np.array([i,i+1,i,i+1]) for i in range(N)] 
masses = np.arange(N) 

heatmap = 0 
xedges = np.linspace(0, N, nbin) 
yedges = np.linspace(0, N, nbin) 

for x, y, mass in IT.izip(xs, ys, masses): 
    hist, xedges, yedges = np.histogram2d(
     x, y, bins=[xedges, yedges], weights=np.ones_like(x)*mass) 
    heatmap += hist 

extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]] 
heatmap = np.flipud(np.rot90(heatmap)) 
fig, ax = plt.subplots() 
ax.imshow(heatmap, extent=extent, interpolation='nearest') 
plt.show() 

产生

enter image description here