# How to count points within adjoining hex grid cells?

I am currently using QGIS, and have developed a vector grid (hexagonal). I have a separate layer with point data. For each grid cell I need to count the number of points in that cell (but also all adjoining cells).

I searched for this problem on Google and Stack Exchange, but no solutions I've been able to find nothing.

Some diagrams to explain, below.

Image 1: I want to calculate a value for this grid cell

Image 2: Value for selected cell = the number of points within this cell + all adjoining cells

## 4 Answers

The first part of your question is easy. Go to `Vector->Analysis Tools->Points in Polygon`. This tool will iterate over all your polygons and add a column (called 'PNTCNT' by default) with the number of points in each polygon.

This tool gives you just a simple count of the number of points in each polygon as the name suggests. You can refine this by using one of the tools from the `Processing ToolBox` such as: `Count points in polygon(weighted)` or `Count unique points in polygon`.

Your second requirement is a little more complicated to automate but fortunately somebody has already done this for you! First perform the basic Point-In-Polygon count as above. Then follow this tutorial, using the script provided and change the sum-field in the script to 'PNTCNT'. This script basically iterates over your polygons, selecting each in turn and then re-selecting all polygons that intersect with the current one (as per your second image). It then iterates over the new set of polygons, summing the values of your point-count field for all neighbours.

You can do this in a spatial data such as Spatialite with these queries:

To get a count of the points only within each grid cell:

``````SELECT g.id, Count(p.id)
FROM points AS p, grid AS g
WHERE ST_Contains(g.geometry, p.geometry)
GROUP BY g.id;
``````

and to query all touching grid cells as well, try:

``````SELECT g.id, Count(p.id) he
FROM points AS p, grid AS g, grid AS g2
WHERE ST_Contains(ST_Union(g.geometry, g2.geometry), p.geometry) AND
ST_Touches(g.geometry, g2.geometry) AND
g.id <> g2.id
GROUP BY g.id;
``````

It's important to note that the second query will take a long time if there are many cells in your grid. So it would be important to add spatial indices and to use them in the query.

The tool in QGIS is "Count Points in Polygons": Vector -> Analysis Tools -> Point in Polygons.

Testing it with extend_grid2 and random_points2 vector layers:

The count is, by default, in PNTCNT field.

Editing Note:

Based in MappaGnosis answer the key is here:

``````.
.
.
from qgis.utils import iface
from PyQt4.QtCore import QVariant

# Replace the values below with values from your layer.
# For example, if your identifier field is called 'XYZ', then change the line
# below to _NAME_FIELD = 'XYZ'
_NAME_FIELD = 'test'
# Replace the value below with the field name that you want to sum up.
# For example, if the # field that you want to sum up is called 'VALUES', then
# change the line below to _SUM_FIELD = 'VALUES'
_SUM_FIELD = 'PNTCNT'
.
.
.
``````

The identifier field ('test' in my case) must be 'string' type (I cloned it from ID). When I ran the script in the Python Console this was the result:

It works nicely.

If i got you correctly, you want to cluster hexagon-grids based on surrounding at distance up to radius of two hexagon (my case is radius of hexagon is 10000 meters and cluster search radius is about 18000 meter)

I would follow as below-

``````        1. Generate center of each grids.
2. Calculate the radius between two hexagon (my case is about 18000   meters) and add bit more(?).
3. Create buffer around each center where radius is that distance (my case is 18000 meters).
4. Then run spatial query to select hexa-grids inside each circle/buffer then dissolve into one polygon and save.
5. Then run Points in Polygon tool on this saved hex-grid clusters polygon - it populate attribute table (PNTCNT field) as you intended.
``````

N.B. You have to get rid of all the points outside the grid at first- for this just run clip operation at first. There may be an automation in pyqgis..

• You have buffered your hex-cells and not the centers as per your description. Buffering the centers will definitely not be correct. Buffering the polygons themselves is better but still inaccurate. Buffering normally adds vertices and rounds corners (as you can see in your image) and therefore, the buffered shape is not identical to the area covered by 7 hexagons. Unless you can constrain the buffers to exactly match the shape of the original polygon (i.e. the buffers must have only 6 vertices with identical relative positions in this case) the count of points will not be correct. – MappaGnosis Apr 13 '15 at 6:25
• NP :) However, you will note that your buffers still include areas outside each set of 7 polygons. I was not clear in my comment above. In this example the buffer polygon must have exactly 18 vertices (not 6) and correspond to the area in pink in your image. Your buffer will include extra areas that are NOT part of the neighboring polygons as they will lie outside the pink area, thus over estimating the actual number of points. Your buffer will be convex, but should in fact should have 6 concave areas. Study the pink area in your image and you'll see what I mean. – MappaGnosis Apr 13 '15 at 7:38