Page 15 sur 18
Classifications
You can use any of these classification method classes:
- QgsClassificationQuantile()
- QgsClassificationEqualInterval()
- QgsClassificationJenks()
- QgsClassificationPrettyBreaks()
- QgsClassificationLogarithmic()
- QgsClassificationStandardDeviation()
Available color ramps
You can check all the ramps availables in your QGIS like that:
default_style = QgsStyle().defaultStyle() available_ramps = default_style.colorRampNames() for ramp in available_ramps: print(ramp)
Equal intervals
# Set layer name and desired params ramp_name = 'Spectral' value_field = 'Population (2024)' num_classes = 10 classification_method = QgsClassificationEqualInterval() layer = QgsProject().instance().mapLayersByName('Countries')[0] format = QgsRendererRangeLabelFormat() format.setTrimTrailingZeroes(True) default_style = QgsStyle().defaultStyle() color_ramp = default_style.colorRamp(ramp_name) renderer = QgsGraduatedSymbolRenderer() renderer.setClassAttribute(value_field) renderer.setClassificationMethod(classification_method) renderer.setLabelFormat(format) renderer.updateClasses(layer, num_classes) renderer.updateColorRamp(color_ramp) layer.setRenderer(renderer) layer.triggerRepaint()
Jenks
# Set layer name and desired params ramp_name = 'PuRd' value_field = 'Population (2024)' num_classes = 20 classification_method = QgsClassificationJenks() layer = QgsProject().instance().mapLayersByName('Countries')[0] format = QgsRendererRangeLabelFormat() format.setTrimTrailingZeroes(True) default_style = QgsStyle().defaultStyle() color_ramp = default_style.colorRamp(ramp_name) renderer = QgsGraduatedSymbolRenderer() renderer.setClassAttribute(value_field) renderer.setClassificationMethod(classification_method) renderer.setLabelFormat(format) renderer.updateClasses(layer, num_classes) renderer.updateColorRamp(color_ramp) layer.setRenderer(renderer) layer.triggerRepaint()
Round zeroes
format = QgsRendererRangeLabelFormat() format.setTrimTrailingZeroes(True)
Decimals
format = QgsRendererRangeLabelFormat() format.setPrecision(2)
Separator
format = QgsRendererRangeLabelFormat() format.setFormat("%1 - %2")
Invert colors
color_ramp = default_style.colorRamp(ramp_name) # Manually invert the color ramp if isinstance(color_ramp, QgsGradientColorRamp): inverted_ramp = QgsGradientColorRamp( color_ramp.color2(), # Use the second color as the start color color_ramp.color1() # Use the first color as the end color ) else: inverted_ramp = color_ramp ... renderer.updateColorRamp(inverted_ramp)