2

Based on this code below, is it possible to use Random Color option in Symbology?

layer = iface.activeLayer()

field_name = 'zona_manejo'
field_index = layer.fields().indexFromName(field_name)
unique_values = layer.uniqueValues(field_index)

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

renderer = QgsCategorizedSymbolRenderer(field_name, category_list)
style = QgsStyle().defaultStyle()
ramp = style.colorRamp('Greens')
renderer.updateColorRamp(ramp)

layer.setRenderer(renderer)
layer.triggerRepaint()

In this case I'm using 'Greens' color ramp, but I'd like to set "Random colors' as this "Color ramp" UI option.

enter image description here

1 Answer 1

4

It's absolutely possible! Just use:

renderer.updateColorRamp(QgsRandomColorRamp())

I modified your script only very slightly:

layer = iface.activeLayer()

field_name = 'zona_manejo'
field_index = layer.fields().indexFromName(field_name)
unique_values = layer.uniqueValues(field_index)

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

renderer = QgsCategorizedSymbolRenderer(field_name, category_list)
renderer.updateColorRamp(QgsRandomColorRamp())
layer.setRenderer(renderer)
layer.triggerRepaint()

See results on a test layer below (I changed only the field name to 'reg_code_8'.

Before:

enter image description here

After:

enter image description here

Incidently, because random colors are the default for the categorized renderer, you don't even need to update the color ramp. You can just use:

layer = iface.activeLayer()

field_name = 'zona_manejo'
field_index = layer.fields().indexFromName(field_name)
unique_values = layer.uniqueValues(field_index)

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

renderer = QgsCategorizedSymbolRenderer(field_name, category_list)
layer.setRenderer(renderer)
layer.triggerRepaint()

It will give you random colors. However, interestingly I notice that the resulting palette is consistently a bit different (colors are not as 'vibrant'). An example:

enter image description here

1
  • 1
    It worked. I will continue to improve my studies in Python.
    – geofausto
    Commented Jul 4, 2022 at 15:00

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.