5

I've got a map composer in QGIS with a polygon layer (attributes: code, area).

enter image description here

I want to add a legend with the codes and the total area for each code. I used the following expression (wrong, as it happens) in the Expression string builder:

@symbol_label ||  ' ' || '(' ||  "area"  || ' ha' || ')'

And in the legend, this is what I get

enter image description here

How can I get what I want?

2
  • 1
    Check out my recent answer here: gis.stackexchange.com/a/385332/107424 Its pretty similar and should solve your issue.
    – MrXsquared
    Commented Feb 8, 2021 at 13:26
  • 2
    You need to set your style and label in the map, not in the map composer. If you have things setup in your map style the Legend of the Print Composer will inherit that. Expression on the Legend Items belongs to a layer not to records in the layer.
    – Jakob
    Commented Feb 8, 2021 at 13:30

2 Answers 2

4

You have to summarize the area by categories, otherwise your expression won't work. As per @Jakobs comment, you have to set this expression in the Legend-tab of the layers properties.

The following should work:

@symbol_label||' ('||sum("area","CODE_18")||' ha)'

This tells QGIS to summarize the field "area" based on the categories of the field "CODE_18".

Side note: You don't have to put pipes between every single sign you want to put in your label.

4
  • It doesn't do the sum. It only shows zeroes s.mail.ru/Axgn/sm4pFaupu
    – jpinilla
    Commented Feb 8, 2021 at 13:29
  • What is the field type of "area"?
    – Erik
    Commented Feb 8, 2021 at 13:31
  • double, precission 2
    – jpinilla
    Commented Feb 8, 2021 at 13:41
  • 1
    As @Jakob suggests in the comment above, the expression must be set up in the layer style legend, and not in the Print Composer
    – jpinilla
    Commented Feb 8, 2021 at 13:46
3

Here is some guidelines about how to solve this : https://docs.qgis.org/3.28/en/docs/user_manual/print_composer/composer_items/composer_legend.html#data-define-the-legend-labels

In your case, this means :

format( '%1 (%2 ha)',
    @symbol_label,
    round( aggregate(@layer, 'sum', "area", filter:= "CODE_18"=@symbol_label) )
  )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.