1

I currently have a Python script that adds a MultiPolygon shapefile to my map within QGIS. Within QGIS, I can apply a categorized symbology render, with the color ramp 'Spectral' going from blue to red, with 55% opacity, for a shapefile called 'Shapefile'. The values within the file under the field 'Intensity' are applied within the categorized symbology (see screenshots). However, I would like to apply this within the Python console. Is there any way I can do this?

enter image description here

enter image description here

UPDATE: Using the code suggested below, I have this: enter image description here

1 Answer 1

4

Try running the code snippet below in the Python console:

default_style = QgsStyle().defaultStyle()
color_ramp = default_style.colorRamp('Spectral') #Spectral color ramp
color_ramp.invert()

layer = QgsProject().instance().mapLayersByName('Shapefile')[0]
field_index = layer.fields().lookupField('Intensity')
unique_values = list(layer.uniqueValues(field_index))
categories = []
for value in sorted(unique_values):
    symbol = QgsSymbol.defaultSymbol(layer.geometryType())
    category = QgsRendererCategory(value, symbol, str(value))
    categories.append(category)
renderer = QgsCategorizedSymbolRenderer('Intensity', categories) 
renderer.updateColorRamp(color_ramp)

# If you really want 4 decimal places (as in your screenshot) uncomment the 3 lines below
#labels = ['1.5000','1.6000','1.8000','2.0000','2.2000','2.4000','2.6000','2.8000','3.0000','3.2000','3.3000']
#for i, n in enumerate(labels):
#    renderer.updateCategoryLabel(i, n)
    
layer.setRenderer(renderer)
layer.setOpacity(0.55)
layer.triggerRepaint()

Example result:

enter image description here

4
  • Hi there. Thank you for your answer. This has nearly answered my question! However, when it is printed out, the values are not in ascending order, so they have varying colours. I have included a screenshot of what I mean above. Do you have any idea how to fix this? Thanks
    – LiamHems
    Feb 22, 2021 at 13:59
  • @LiamHems, Yes- sorting the list of unique values should fix it. I have updated my answer.
    – Ben W
    Feb 22, 2021 at 21:35
  • Thank you very much for your help! It was greatly appreciated and it works perfectly, exactly what I wanted :)
    – LiamHems
    Feb 23, 2021 at 9:30
  • No problem, glad it helped!
    – Ben W
    Feb 23, 2021 at 10:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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