I extensively use ArcPy, recently needed to apply a specific color ramp on a single band raster and export it. Arcpy does not allow me to apply color ramp and save the raster with the applied color ramp. However, QGIS has the option to do that.

I created a new color ramp in QGIS 2.18.20 and name it to "Yield", which is 28th (defaultColorRampNames[27]) item in the color ramp list. Is there any PyQGIS codes that can automatically apply the color ramp to the raster. I have the codes to save the raster after applying the color ramp but struggling to find a way to apply that.

Followed the codes from Using QGIS GUI predefined colorramps in Python console / PyQGIS? - but first couples of lines are working not the last three lines. The following codes are working -

#accessing the raster layer
vl = iface.activeLayer()

## get default style
myStyle = QgsStyleV2().defaultStyle()

## get a list of default color ramps [u'Blues', u'BrBG', u'BuGn'....]
defaultColorRampNames = myStyle.colorRampNames()

## setting ramp to "Yield" which was recently created
ramp = myStyle.colorRamp(defaultColorRampNames[27])

But, the codes provided below seems like for a shapefile, not sure what to use for the raster layer

# set up an empty categorized renderer and assign the color ramp
renderer = QgsCategorizedSymbolRendererV2(field, [])

Your Answer


Browse other questions tagged or ask your own question.