1

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

Yash Dwivedi
  • 71
  • 1
  • 5
  • You don't need a plot for this. Just count the points in the input collection (`pos_table`, I suppose) where x and y are within some bounds of your liking. – mkrieger1 Jan 02 '20 at 14:56
  • I'm sorry I don't quite understand what you mean by this.. – Yash Dwivedi Jan 02 '20 at 14:59
  • Does this answer your question? [Scatterplot Contours In Matplotlib](https://stackoverflow.com/questions/19390320/scatterplot-contours-in-matplotlib) – Diziet Asahi Jan 02 '20 at 15:25

1 Answers1

1

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.

Andrea
  • 2,932
  • 11
  • 23
  • Yes, this is what i need, thanks. However i have not generated my plot like you have. My plot, is generated from a panda table. How would I go about doing what you did from that? – Yash Dwivedi Jan 03 '20 at 10:46
  • 1
    As far as I know, pandas still not include a `hist2d` plot function yet, but you still can use it together with `matplotlib`. I will edit my answer – Andrea Jan 03 '20 at 10:57
  • Thank you very much, I was able to adapt the code! Although now the bar on the right hand side is missing? – Yash Dwivedi Jan 03 '20 at 12:37
  • Regarding `pos_table = pd.DataFrame({'x':x, 'y':y})`, what is `pd` referring to? – dfcoelho Sep 10 '20 at 21:16
  • To the pansas library: import pandas as pd – Andrea Sep 10 '20 at 21:17