pythonnumpyhistogram2d

Standard deviation from numpy 2d histogram


Is there a method to determine the standard deviation in each bin using the numpy histrogram2d method, given a series of 2d coordinates along with weighted values for each coordinate?


Solution

  • It's not directly possible with numpy's histrogram2d but with scipy.stats.binned_statistic_2d it can be done quite easily.

    from scipy import stats
    
    x = np.random.rand(10000)
    y = np.random.rand(10000)
    z = np.random.rand(10000)
    binx = np.linspace(0,x.max(), 100)
    biny = np.linspace(0,y.max(), 100)
    hist = stats.binned_statistic_2d(x, y, z, statistic='std', bins=[binx, biny])
    plot_x, plot_y = np.meshgrid(binx, biny)
    
    fig, ax = plt.subplots(figsize=(5,5))
    pc = ax.pcolormesh(plot_x, plot_y, hist[0].T, cmap="inferno")
    ax.set_aspect('equal')
    cbar=fig.colorbar(pc,shrink=0.725)
    fig.tight_layout()
    

    enter image description here

    The statistic option can also take different things like mean, median or a user-defined function, see the documentation for more details.