QGIS – How to Create a Dynamic Label for a Polygon Layer Summing Line Length and Other Attributes

labelingqgissummarizing

For an agroforestry design in QGIS I am trying to add dynamic labels to an area polygon that displays the number of rows, total length and the total number of trees that are in the design.

So far I manged to create a label for the area that list the name of the area & number of rows, but I am struggling to add the total sum of tree row lenght and the total number of tree to be planted to the labels.

I managed to add a new field (number_of_rows) to the attribute table and using the attribute form I linked this function expression layer_property(´treeLinelayer_ID´),´features_count´ function, so that it always has an up to date count of tree rows (the designs are still changing)

I was able to add dynamic line length and number_of tree labels to the individual tree lines, but not to the polygon file. there are many lines and in the end there will be many different areas, so I would really like to show the total length and number of trees per area.

Any suggestions on how to go about this? The sum line lengths in the vector analysis tools does not seem to be useful in this case, because first of all, the labels need to automatically change according to future updates in design parameters (distance between tree rows & distance between trees).

Best Answer

You can use the overlay_intersects() function to grab aggregates from another layer.

For example to count the number of features from your Tree Line layer intersecting the polygon:

array_length(overlay_intersects('tree_line_layer',"tree_count_field"))

To sum the number of trees from the Tree Line features intersecting the polygon:

array_sum(overlay_intersects('tree_line_layer',"tree_count_field")) 

To sum the length of Tree Line features intersecting the polygon:

array_sum(overlay_intersects('tree_line_layer',$length))

You can use this in the label expression for your polygon and it will dynamically update:

enter image description here

Related Question