3

I was wondering if there is an existing tool/way to aggregate an attribute based on the active symbology of a layer.

For instance, if I have a point layer with population and distance from the city center for each point and I create a specific symbology for the distance (let's say 0-1km, 1-5km 5++km) to get the total number of people within each class.

I would like to avoid creating dummy reclassified attributes if possible.

8
  • Are you talking about something like aggregate('pointlayer','sum',"population","distance"<1000)? Just adjust the distance for each symbology class.
    – MrXsquared
    Jul 6, 2020 at 11:57
  • yeah, something like this, but i want it to read directly from the symbology so that i don't have to it manually.
    – vagvaf
    Jul 6, 2020 at 12:09
  • What do you mean with reading data from the symbology? Your symbology is based on a field or on an expression?
    – Val P
    Jul 6, 2020 at 12:56
  • on a specific field
    – vagvaf
    Jul 6, 2020 at 13:37
  • So you want to aggregate based on a specific field, not on the symbology, did I understand you right? Would using the aggregated algorithm solve your problem? See the documentation here: docs.qgis.org/3.10/en/docs/user_manual/processing_algs/qgis/…
    – Babel
    Jul 6, 2020 at 14:36

1 Answer 1

0

So this is more or less what I did. It was fine for me to just have the results printed in the terminal.

The symbology was drawn from a qml file and I don't know if this works with ad-hoc symbologies.

Finally, I am sure that there is a way to integrate the aggregate function, but for I just needed to sum.

from PyQt5.QtXml import QDomDocument
import xml.etree.ElementTree as ET

def sumBySymbologyClass(layer, attribute):
    layer.exportNamedStyle(d)
    s = d.toString()
    root = ET.fromstring(s)

    for attr in root.iter('renderer-v2'):
            classified_attribute=attr.attrib['attr']
            
    i=0
    for elem in root.iter('range'):
        class_pop=[]
        lower = elem.attrib['lower']
        upper = elem.attrib['upper']
        if i==0:
            features = layer.getFeatures('"{}" >= {} AND "{}" <= {}'.format(classified_attribute, lower, classified_attribute, upper))
        else:
            features = layer.getFeatures('"{}" > {} AND "{}" <= {}'.format(classified_attribute, lower, classified_attribute, upper))
        i+=1
        for feature in features:
            sumAttribute = feature[attribute]
            class_pop.append(sumAttribute)
        print('{},{},{},{}\n'.format(classified_attribute, lower, upper, sum(class_pop)))

Your Answer

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

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