[GIS] Using attribute data for legend labeling in QGIS

labelinglegendqgis

For features in a map it is possible to stuck data from the attribute table together and get a data driven label. I try to do this for my legend labels. I want to combine values from my attribute table to get a customised label. I want a legend with rule based label entries. Rather similar to "rule based style" but with combined column values.

enter image description here

For example:
Klass_1 (3 %)

For instance Klass_1 is from a column "Klass" and 3 % from a column "Percentage".

Thats the plan:

enter image description here

How can I do this?

Best Answer

I've sort of replicated your situation.

enter image description here

Not sure if there's an easier way to do it, but the following code snippet works for me (I'm using QGIS v.2.8). To use it, activate your layer in the ToC, open the QGIS Python console, and copy&paste the code there.

lyr = iface.activeLayer()
renderer = lyr.rendererV2()
children = renderer.rootRule().children()
fieldName1 = "Klass"
fieldName2 = "Percentage"

for child in children: # Iterate through groups
    if child.filter():
        feat = next(lyr.getFeatures(QgsFeatureRequest(child.filter())), None)
        if feat:
            child.setLabel( feat.attribute(fieldName1) + " (" + feat.attribute(fieldName2) + ")")
        for subChild in child.children(): # Iterate through subgroups
            if subChild.filter():
                feat = next(lyr.getFeatures(QgsFeatureRequest(subChild.filter())), None)
                if feat:
                    subChild.setLabel( feat.attribute(fieldName1) + " (" + feat.attribute(fieldName2) + ")")

The code assumes fields to concatenate are of type String.

After the code runs, open the layer properties and you should see the new concatenated labels. Click on Ok to refresh your legend.

I obtain this:

enter image description here

Let me know if you have troubles with it.

Related Question