A color ramp allows you to render a raster using just a few colors to represent different ranges of cell values that have similar meaning, in order to group them. The approach that will be used in this recipe is the most common way to render elevation data.
You can download a sample DEM from https://geospatialpython.googlecode.com/files/dem.zip, which you can unzip in a directory named rasters
in your qgis_data
directory.
In the following steps, we will set up objects to color a raster, create a list establishing the color ramp ranges, apply the ramp to the layer renderer, and finally add the layer to the map. To do this, we need to perform the following steps:
QtGui
library for color objects in the QGIS Python Console:from PyQt4 import QtGui
lyr = QgsRasterLayer("/Users/joellawhead/qgis_data/rasters/dem.asc", "DEM")
s = QgsRasterShader()
c = QgsColorRampShader()
INTERPOLATED
shader:c.setColorRampType(QgsColorRampShader.INTERPOLATED)
i = []
i.append(QgsColorRampShader.ColorRampItem(400, QtGui.QColor('#d7191c'), '400')) i.append(QgsColorRampShader.ColorRampItem(900, QtGui.QColor('#fdae61'), '900')) i.append(QgsColorRampShader.ColorRampItem(1500, QtGui.QColor('#ffffbf'), '1500')) i.append(QgsColorRampShader.ColorRampItem(2000, QtGui.QColor('#abdda4'), '2000')) i.append(QgsColorRampShader.ColorRampItem(2500, QtGui.QColor('#2b83ba'), '2500'))
c.setColorRampItemList(i)
s.setRasterShaderFunction(c)
ps = QgsSingleBandPseudoColorRenderer(lyr.dataProvider(), 1, s)
lyr.setRenderer(ps)
QgsMapLayerRegistry.instance().addMapLayer(lyr)
While it takes a stack of four objects to create a color ramp, this recipe demonstrates how flexible the PyQGIS API is. Typically, the more objects it takes to accomplish an operation in QGIS, the richer the API is, giving you the flexibility to make complex maps.
Notice that in each ColorRampItem
object, you specify a starting elevation value, the color, and a label as the string. The range for the color ramp ends at any value less than the following item. So, in this case, the first color will be assigned to the cells with a value between 400 and 899. The following screenshot shows the applied color ramp.