I am trying to find the most number of 'bands' (band A, B, C) in each postcode area. The 'bands' is represented in points and I would like to output into maps(polygons). Is there a way to do a spatial join (i.e. join attributes by location) and get it to calculate the mode (most times that reoccurs). Using QGIS 2.18.13
-
Maybe you could rasterize your bands and use Zonal Statistics plugin to get the mode (majority) for each polygon. The most frequently occurring value is listed as majority in the tool.– ZrSiO4Commented Nov 23, 2017 at 16:56
-
how to I rasterize the bands?– BernieCommented Nov 24, 2017 at 14:09
-
@Kazuhito understood your question better and provided an elegant solution. For some reason, I thought the "bands" point file had some numeric value to it one could rasterize even though you clearly show them as A,B,C.– ZrSiO4Commented Nov 24, 2017 at 17:08
-
Thanks @ZrSiO4 sorry it seems I have missed your comment for some reason. OP did not specify the volume of data points, but rasterize would be more efficient approach if there are many points. A,B,C can be translated to 1,2,3 in such occasion.– KazuhitoCommented Nov 28, 2017 at 11:00
1 Answer
In this example I used refFunctions plugin and a Virtual Layer.
Sample Data
- One point layer (bands_pt.shp) with
id
,bands
fields; 8 records. - One polygon layer (postcodes_poly.shp) with
id
,postcode
fields; 2 records.
Workflow
(1) Copy postcode
field from the polygon layer to the point layer; which falls within the designated polygon (ie postcode 1234
and 5678
).
- Open attribute table of point layer (bands_pt).
- Create a new text field
postcode
=geomwithin('postcodes_poly', 'postcode')
.
(2) Create a Virtual Layer
Layer | Add Layer | Add/Edit Virtual Layer
- [Import] bands_pt
A sample query is:
SELECT bands, postcode, max(cnt)
FROM(SELECT postcode, bands, count(*) AS cnt
FROM bands_pt
GROUP BY postcode, bands)
GROUP BY postcode
If you open the attribute table of this virtual layer
it will show combination of most frequent band (and its count) in each postcode area.
EDIT (as requested)
To combine the Mode value with the postcodes
polygon, try following query:
SELECT *
FROM(SELECT postcode, bands, max(cnt)
FROM(SELECT postcode, bands, count(*) AS cnt
FROM bands_pt
GROUP BY postcode, bands)
GROUP BY postcode) AS a
INNER JOIN postcode_poly
ON a.postcode = postcode_poly.postcode
Before changing the syntax, please do not forget to [import] postcodes_poly layer along with the bands_pt (as already imported in the above step (2)-2).
-
how do I then save the virtual layer into a polygon shapefile? when i save it, the symbol becomes a line.– BernieCommented Nov 28, 2017 at 10:21
-
@Bernie Can you explain what do you mean by "a polygon"? I thought your question was about mode, which is given as a table here. Do you want to attach the value to your postcode polygon, perhaps?– KazuhitoCommented Nov 28, 2017 at 10:25
-
-