2013-06-21 45 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