I am trying to give proper format to a raster (from a GEOTIFF file, previously generated). I need to show it with 3 classes, using discrete classification and equal intervals. This is easy to do from within the GUI, but I want to do it programatically. I have tried the two following approaches.
Method #1:
raster = QgsProject.instance().mapLayersByName('itp')[0]
fcn = QgsColorRampShader()
fcn.setColorRampType(QgsColorRampShader.Discrete)
lst = [ QgsColorRampShader.ColorRampItem(22.6, QColor(0,255,0)),
QgsColorRampShader.ColorRampItem(23.2, QColor(255,255,0)),
QgsColorRampShader.ColorRampItem(100.0, QColor(255,0,0)) ]
fcn.setColorRampItemList(lst)
shader = QgsRasterShader()
shader.setRasterShaderFunction(fcn)
renderer = QgsSingleBandPseudoColorRenderer(raster.dataProvider(), 1, shader)
raster.setRenderer(renderer)
raster.triggerRepaint()
This method works, but the labels for the groups are empty (I do not know how to fix that), and I have to manually specify the expected ranges on the ColorRampShader, which is unconvenient. So I tried the following:
Method #2:
raster = QgsProject.instance().mapLayersByName('itp')[0]
colRamp = QgsGradientColorRamp (QColor(0,255,0), QColor(255,0,0), False)
renderer = QgsSingleBandPseudoColorRenderer(raster.dataProvider(), 1)
renderer.createShader(colRamp, QgsColorRampShader.Discrete, QgsColorRampShader.EqualInterval, 3)
raster.setRenderer(renderer)
raster.triggerRepaint()
The problem is this second method does not work at all... ...until I open the symbology properties and click accept in GUI. Calling triggerRepaint() does not help.
So, my question is: Why Method #2 does not work? I could not find any funcion to force refresh the calculation inside the docs, and this method does not serve my purpose if I have to manually open every output file.
And, related to this: Is there any way to specify the number of decimal/significant digits of the group labels?