Sunday, 24 May 2015

QGIS how to sum a certain vector field inside a polygon and populate a field in the polygon?


I have a polygon with vector point civic addresses inside it. Each civic address has a different number residence. I want to sum the total number of residence inside that polygon and it populate a field in the polygon. It is easy to do it manually but I need it to auto-update if another civic address is added or the number of residence changes. I'm new to QGIS and tried an expression but it didn't seem like I was able to reference the field of another point. How would I go about doing this?



Answer



It can be done in Field Calculator with function aggregate(). In point layer create new field with field calculator expression like this:


aggregate(
layer:= 'points_layer_name',
aggregate:='sum',
expression:=residence_number_field_name,
filter:=intersects($geometry, geometry(@parent))
)


Where layer is polygon layer name written like string, aggreagate is aggregate function, expression is field from values will be taken and filter is filtering features based on expression (in this case interesects layer geometry with geometry of parent layer).


For more info check Aggregates QGIS documentation.


You can use virtual fields for automatic updates, but keep in mind that these fields are stored in project, not in your data. If you export the layer virtual field is exported also, but ase normal field.


You can also set the expression as Default value in Attributes Form settings in Layer Properties (Attribute form setting documentation). But in this case it will update only new or edited polygon features (not when you add or edit points). Values have to be updated manually in attribute table rewriting field itselves with "residence_number_field_name" = "residence_number_field_name".


I also posted a similar answer for the opposite case (points taking polygons attribute values) How to refer to another layer in the field calculator?


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...