According to the PyQGIS Cookbook, a color ramp can be assigned in the following way:

lst = [ QgsColorRampShader.ColorRampItem(0, QColor(0,255,0)), \
    QgsColorRampShader.ColorRampItem(255, QColor(255,255,0)) ]
fcn = rlayer.rasterShader().rasterShaderFunction()

However, this code appears to be old, because setColorShadingAlgorithm is not present in QGIS 2.2.0. This bug report states that setDrawingStyle can be used instead, but I haven't been able to assign a color ramp through its use.

How would I assign a color ramp through PyQGIS, using setDrawingStyle or otherwise?

  • Though not an answer to my specific question, I found an easier way to accomplish what I'm trying to automate. This question/answer shows how to load a saved style using PyQGIS. Rather than specifying the color ramp using PyQGIS, I can manually save a style in a .qml file, then load this file using PyQGIS. – Chris S. Oct 19 '14 at 14:44

Based in this answer, What is the replacement for 'setColorShadingAlgorithm' in QGIS 2.6?, I include the following code where it is also employed the procedure substitute for 'setColorShadingAlgorithm' ('setRasterShaderFunction', objet of the QgsRasterShader class). This code get the minimum and maximum values of the raster, by using some dataProvider class methods, to calculate the ColorRampItem's .

from PyQt4.QtCore import *
from PyQt4.QtGui import *

layer = iface.activeLayer()

renderer = layer.renderer()
provider = layer.dataProvider()

ver = provider.hasStatistics(1, QgsRasterBandStats.All)

stats = provider.bandStatistics(1, QgsRasterBandStats.All,extent, 0)

if ver is not False:
    print "minimumValue = ", stats.minimumValue

    print "maximumValue = ", stats.maximumValue

if (stats.minimumValue < 0):
   min = 0  

    min= stats.minimumValue

max = stats.maximumValue
range = max - min
add = range//2
interval = min + add

colDic = {'red':'#ff0000', 'yellow':'#ffff00','blue':'#0000ff'}

valueList =[min, interval, max]

lst = [QgsColorRampShader.ColorRampItem(valueList[0], QColor(colDic['red'])),\
       QgsColorRampShader.ColorRampItem(valueList[1], QColor(colDic['yellow'])), \
       QgsColorRampShader.ColorRampItem(valueList[2], QColor(colDic['blue']))]

myRasterShader = QgsRasterShader()
myColorRamp = QgsColorRampShader()


myPseudoRenderer = QgsSingleBandPseudoColorRenderer(layer.dataProvider(), 



When this code was running in the Python Console, with a single gray raster band (minimum value = 1323.0, maximumValue = 3556.0), the image resulting had the following pseudocolor renderer:

enter image description here

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.