assume there is a grid with some points in it just like in the plot below. 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 !
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()
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With