pythonmatplotlibplotcelllist

Splitting a graph into squares


I have a plot of n number of points in a scatter graph. I want to split the plot into a grid of squares of x length and then assign each point in my graph a certain square from the grid I just made. How would I go about doing this in Python?

The code for the graph is this:

diagram = pos_table.plot.scatter('x', 'y', c = 'purple', s = 2)

which results in:

enter image description here

How would I split this into squares and then count the number of points in each square? Thanks


Solution

  • I believe you are looking for hist2d, here's a snippet that might help you:

    import numpy as np
    import pandas as pd
    
    np.random.seed(42)
    x = np.random.uniform(0,40,size=20)
    y = np.random.uniform(0,40,size=20)
    
    pos_table = pd.DataFrame({'x':x, 'y':y})
    diagram = pos_table.plot.scatter('x', 'y', c = 'purple', s = 2)
    plt.show()
    

    enter image description here

    import matplotlib.pyplot as plt
    bins = np.arange(0,41,10)
    h = plt.hist2d(pos_table.x, pos_table.y, bins=(bins, bins))
    plt.colorbar(h[3])
    

    enter image description here

    bins defines the square grid (4X4) in the example, and h[3] contains the info about the number of points contained in each bin.