7

I use the following code to apply pseudo color into a NDVI raster.

rlayer =layer = iface.activeLayer()
#stats = rlayer.dataProvider().bandStatistics(1, QgsRasterBandStats.Range)
#min = stats.minimumValue
#max = stats.maximumValue
fnc = QgsColorRampShader()
fnc.setColorRampType(QgsColorRampShader.Interpolated)
lst = [QgsColorRampShader.ColorRampItem(-1, QColor(0,0,0)),\
       QgsColorRampShader.ColorRampItem(-0.5, QColor(0,0,255)),\
       QgsColorRampShader.ColorRampItem(0, QColor(255,0,0)),\
       QgsColorRampShader.ColorRampItem(0.5, QColor(0,255,255)),\
       QgsColorRampShader.ColorRampItem(1, QColor(0,255,0))]
fnc.setColorRampItemList(lst)
shader = QgsRasterShader()
shader.setRasterShaderFunction(fnc)
renderer = QgsSingleBandPseudoColorRenderer(rlayer.dataProvider(), 1, shader)
rlayer.setRenderer(renderer)
rlayer.triggerRepaint()
iface.layerTreeView().refreshLayerSymbology(rlayer.id())

The colors are applied and viewed as supposed but the legend for the raster, in layers panel, changes into 0-255 range instead of -1 to 1, as u can see in the picture.

symbology range changes from -0.32 - 0.93 to 0-255

What am I missing ?? Is there any class I should use to 'play' with the symbology ?

FYI, reading and using the stats of the raster band has no effect.

1 Answer 1

6

You have to set minimum and maximum values for "Singleband pseudocolor" renderer.

renderer = QgsSingleBandPseudoColorRenderer(rlayer.dataProvider(), 1, shader)
renderer.setClassificationMax(1)
renderer.setClassificationMin(-1)

enter image description here

enter image description here

3
  • Thank you so much, it worked ! Do you know if it is possible to display also the -0.5, 0 and 0.5 values ?
    – Lazikas
    Mar 12, 2023 at 0:55
  • In order to display decimal values, the data type of the raster must be float, not integer or not byte. I noticed that fact, while looking for an answer to your question. Mar 12, 2023 at 9:35
  • You can display only min and max values because it is a color ramp. If the values (-1, -0.5, 0, 0.5, 1) are discrete values then you can display them using QgsPalettedRasterRenderer instead of QgsSingleBandPseudoColorRenderer. In that case, the legend isn't displayed as color ramp but discrete color. Please check this answer Mar 12, 2023 at 20:07

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.