7

I have created this code to categorize my layer symbology based on the attribute plant_allo. However I still have to press the classify button which I also want to automate in PyQGIS. Can anyone help me with this last step?

enter image description here

Here is my code:

year = 2030
allocated_regions = QgsVectorLayer(output_folder + "regions_w_plant_alloc_" + str(year) + ".shp", "allocated_regions_" + str(year), "ogr")
QgsProject.instance().addMapLayer(allocated_regions)

# Field name
expression = 'plant_allo'
# Set the categorized renderer
renderer = QgsCategorizedSymbolRenderer(expression)
allocated_regions.setRenderer(renderer)
allocated_regions.triggerRepaint()

1 Answer 1

6

According to Documentation, you have to either explicitly specify category list or add later by calling addCategory().

allocated_regions = iface.activeLayer()

field_name = 'plant_allo'
field_index = allocated_regions.fields().indexFromName(field_name)
unique_values = allocated_regions.uniqueValues(field_index)

# create category list
category_list = []
for value in unique_values:
    symbol = QgsSymbol.defaultSymbol(allocated_regions.geometryType())
    category = QgsRendererCategory(value, symbol, str(value))
    category_list.append(category)

# create renderer by specifying category list
renderer = QgsCategorizedSymbolRenderer(field_name, category_list)
style = QgsStyle().defaultStyle()
ramp = style.colorRamp('Viridis')
renderer.updateColorRamp(ramp)

allocated_regions.setRenderer(renderer)
allocated_regions.triggerRepaint()
0

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.