Home > Software design >  Histogram from two coupled arrays
Histogram from two coupled arrays

Time:11-11

I have two arrays: one for particles locations X and one for the corresponding velocities V. I want to create a histogram for the particle locations, where each bin width is 1, and for each bin I want to calculate the variance of the associated velocities of the particles in that particular bin.

Doing the location histogram is straightforward:

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)

However, I want to calculate the variance of the velocities for the particles in each bin according to V vector (if there are 3 particles in the bin centered at -3, I want to calculate the variance of the 3 velocity values). I’m not sure how to do it efficiently, since there is no tracking of the mapping from the X vector to the histogram.

Any ideas on how to approach this problem?

Thank you!

CodePudding user response:

You may want to use the function scipy.stats.binned_statistics.

Here is an example.

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()
  • Related