pythonnumpymatplotlibscipyhistogram2d

Is there a way to bin a set of 2D coordinates in Python


Hey so I have a 2D array of x,y coordinates in the form: [[x0,y0],[x1,y1],....,[xn,yn]]. These coordinates lie within a rectangle of size x_length and y_length. I want to split the rectangle into a set of squares and find how many coordinates lie within each square, if that makes any sense. Using the 2D histogram function (np.histogram2d()) I've managed to do something similar, but it doesn't tell me the actual number of points within each bin (which is what I'm trying to get). I've attached an example of the 2D histogram for reference. enter image description here enter image description here


Solution

  • values, xbins, ybins = np.histogram2d(x=a[:,0], y=a[:,1]) gives the actual number of points of each bin into values. Note that many matplotlib functions index first by y, so you might need values.T depending on the use case.

    Here is a visualization showing how the values can be used.

    import matplotlib.pyplot as plt
    import matplotlib.patheffects as path_effects
    import numpy as np
    
    x = np.linspace(-0.212, 0.233, 50)
    y = x * 0.5 - 0.01
    
    hist, xbins, ybins = np.histogram2d(x=x, y=y, bins=(np.arange(-0.25, 0.25001, 0.02), np.arange(-0.15, 0.15001, 0.02)))
    
    fig, ax = plt.subplots(figsize=(11, 6))
    for i in range(len(xbins) - 1):
        for j in range(len(ybins) - 1):
            text = ax.text((xbins[i] + xbins[i + 1]) / 2, (ybins[j] + ybins[j + 1]) / 2, f"{hist[i, j]:.0f}",
                           color='cornflowerblue', size=16, ha='center', va='center')
            text.set_path_effects([path_effects.Stroke(linewidth=3, foreground='white', alpha=0.6), path_effects.Normal()])
    ax.plot(x, y, '-ro')
    ax.set_xlim(xbins.min(), xbins.max())
    ax.set_ylim(ybins.min(), ybins.max())
    ax.set_xticks(xbins + 0.0001, minor=True)
    ax.set_yticks(ybins + 0.0001, minor=True)
    ax.grid(which='minor', color='dodgerblue', ls='--')
    ax.set_aspect(1)
    plt.show()
    

    visualizing np.histogram2d