Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Countig points in boxes of a grid

Tags:

python

assume there is a grid with some points in it just like in the plot below. Demo My goal is to count the points per box of the grid. And this is my first try.

            for tupel in point_list:
               a=0
               b=0
               for i in self.boxvector:
                  if tupel[0] < i:
                     a=self.boxvector.index(i)-1
                     break

               for i in self.boxvector:
                  if tupel[1] < i:
                     b=self.boxvector.index(i)-1
                     break

               farray[a][b]+=1

It works, but it is slow. Are there to speed it a little up?

I use a variable named boxvector to define the grid. In this example boxvector is: boxvector = [-1., -.5, 0, .5, 1.]. The grid is always quadratic with maxima at -1 and 1. The boxes are represented through farray, which looks like farray = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]. So that there is one value for each box which is incremented every time the algorithm finds a point in the corresponding box. point_list has the form point_list = [(x0,y0),(x1,y1),(x3,y3), ...]

Thank you for your help !

like image 322
MaxPowers Avatar asked Dec 26 '22 23:12

MaxPowers


2 Answers

Seeing as you appear to already be using matplotlib, just use numpy.histogram2d.

As an example:

import numpy as np
import matplotlib.pyplot as plt

t = np.linspace(0, 4*np.pi, 100)
x = np.cos(3 * t)
y = np.sin(t)

gridx = np.linspace(-1, 1, 5)
gridy = np.linspace(-1, 1, 5)

grid, _, _ = np.histogram2d(x, y, bins=[gridx, gridy])

plt.figure()
plt.plot(x, y, 'ro')
plt.grid(True)

plt.figure()
plt.pcolormesh(gridx, gridy, grid)
plt.plot(x, y, 'ro')
plt.colorbar()

plt.show()

enter image description here

enter image description here

like image 107
Joe Kington Avatar answered Jan 16 '23 04:01

Joe Kington


See also

matplotlib.nxutils.pnpoly()

and

matplotlib.nxutils.points_inside_poly()

Very fast and efficient points inside polygons utilities. You would just have to create the polygons based on the vertices of the grid corners.

http://matplotlib.sourceforge.net/api/nxutils_api.html

like image 30
reptilicus Avatar answered Jan 16 '23 02:01

reptilicus