来自两个耦合阵列的直方图
Histogram from two coupled arrays
我有两个数组:一个用于粒子位置 X
,另一个用于相应的速度 V
。
我想为粒子位置创建一个直方图,其中每个 bin 宽度为 1,并且对于每个 bin 我想计算该特定 bin 中粒子的相关速度的方差。
做位置直方图很简单:
import numpy as np
import matplotlib.pyplot as plt
X = np.random.randn(1000)
V = 3*np.random.randn(1000) + 40
bins = np.arange(int(X.min()) - 0.5, int(X.max())+1.5, 1)
plt.hist(X, bins=bins, facecolor = '#2ab0ff', edgecolor='#169acf', linewidth=0.7)
但是,我想根据V
向量计算每个bin中粒子的速度方差(如果bin中有3个粒子以-3为中心,我想计算方差3 个速度值)。
我不确定如何有效地做到这一点,因为没有跟踪从 X
向量到直方图的映射。
关于如何解决这个问题有什么想法吗?
谢谢!
您可能需要使用函数 scipy.stats.binned_statistics。
这是一个例子。
import numpy as np
from scipy.stats import binned_statistic
import matplotlib.pyplot as plt
X = np.random.randn(1000)
V = 3*np.random.randn(1000) + 40
hist, bins, stst = binned_statistic(X, V, statistic='std')
bin_centres = (bins[1:] + bins[:-1]) / 2
plt.plot(bin_centres, hist)
plt.show()
我有两个数组:一个用于粒子位置 X
,另一个用于相应的速度 V
。
我想为粒子位置创建一个直方图,其中每个 bin 宽度为 1,并且对于每个 bin 我想计算该特定 bin 中粒子的相关速度的方差。
做位置直方图很简单:
import numpy as np
import matplotlib.pyplot as plt
X = np.random.randn(1000)
V = 3*np.random.randn(1000) + 40
bins = np.arange(int(X.min()) - 0.5, int(X.max())+1.5, 1)
plt.hist(X, bins=bins, facecolor = '#2ab0ff', edgecolor='#169acf', linewidth=0.7)
但是,我想根据V
向量计算每个bin中粒子的速度方差(如果bin中有3个粒子以-3为中心,我想计算方差3 个速度值)。
我不确定如何有效地做到这一点,因为没有跟踪从 X
向量到直方图的映射。
关于如何解决这个问题有什么想法吗?
谢谢!
您可能需要使用函数 scipy.stats.binned_statistics。
这是一个例子。
import numpy as np
from scipy.stats import binned_statistic
import matplotlib.pyplot as plt
X = np.random.randn(1000)
V = 3*np.random.randn(1000) + 40
hist, bins, stst = binned_statistic(X, V, statistic='std')
bin_centres = (bins[1:] + bins[:-1]) / 2
plt.plot(bin_centres, hist)
plt.show()