Although this question is relatively old, I was struggling for quite some time to get it working as I wanted (for QGIS 3).
My goal is to just load a layer, and get some single band pseudocolor styling to avoid having to click through the properties repeatedly. And I'd like to use one of the default QGIS colormaps.
It's worth noting that the QgsStyle().defaultStyle().colorRamp object has a .color() method which does the interpolation for you; no need to parse the ramp properties like suggested here:
How can singleband pseudocolor style's values be computed using PyQgis
from typing import List
from qgis.core import (
QgsRasterBandStats,
QgsColorRampShader,
QgsRasterShader,
QgsSingleBandPseudoColorRenderer,
QgsStyle,
)
def color_ramp_items(
colormap: str, minimum: float, maximum: float, nclass: int
) -> List[QgsColorRampShader.ColorRampItem]:
delta = maximum - minimum
fractional_steps = [i / nclass for i in range(nclass + 1)]
ramp = QgsStyle().defaultStyle().colorRamp(colormap)
colors = [ramp.color(f) for f in fractional_steps]
steps = [minimum + f * delta for f in fractional_steps]
return [
QgsColorRampShader.ColorRampItem(step, color, str(step))
for step, color in zip(steps, colors)
]
def pseudocolor_styling(layer, colormap: str, nclass: int) -> None:
stats = layer.dataProvider().bandStatistics(1, QgsRasterBandStats.All)
minimum = stats.minimumValue
maximum = stats.maximumValue
ramp_items = color_ramp_items(colormap, minimum, maximum, nclass)
shader_function = QgsColorRampShader()
shader_function.setClassificationMode(QgsColorRampShader.EqualInterval)
shader_function.setColorRampItemList(ramp_items)
raster_shader = QgsRasterShader()
raster_shader.setRasterShaderFunction(shader_function)
renderer = QgsSingleBandPseudoColorRenderer(layer.dataProvider(), 1, raster_shader)
layer.setRenderer(renderer)
layer.triggerRepaint()
Example use:
layer = QgsProject.instance().mapLayersByName("example_layer")[0]
pseudocolor_styling(layer, colormap="Viridis", nclass=10)
Where "example layer" is the name of the layer in the Layers Panel.
It'll error if you ask for a colormap that isn't available (e.g. "viridis", lower case).