QGIS – Numbering Polygons from North-East to South-West

qgis

I'm working with polygon outputs of an algorithm, where each polygon has a (seemingly) random ID (that is due to some internal logic of the algorithm).

I'd like to assign spatially meaningful IDs:
A unique ID for each polygon that is based on the location of each polygon within the dataset, going from North to South and East to West (i.e. the Northeastern-most polygon gets the ID 1, the next in Southwest-direction gets ID 2, 3, … and so forth).

Is there a tool in QGIS for "spatially sensitive sequential numbering"?

Example numbering of a polygon dataset as asked for...

I have some ideas how to do it "programmatically" (e.g. extract coordinates of each polygon extent (upper left corner) and sort by these coordinates, then do a sequential numbering), but I'm hoping there are built-in functions for this…

Best Answer

You can create a Virtual Layer with the query:

SELECT ROW_NUMBER() OVER( ORDER BY ST_MAXY(geometry) DESC, ST_MAXX(geometry) DESC) AS id, *
FROM patch

Which is numbering the rows in the order of maxy -> miny and maxx -> minx using ROW_NUMBER function. The output will be temp so you need to save it to file.

enter image description here

You can also try order by centroid x/y coordinates.

Related Question