A graduated vector layer symbol renderer is the vector equivalent of a raster color ramp. You can group features into similar ranges and use a limited set of colors to visually identify these ranges. In this recipe, we'll render a graduated symbol using a polygon shapefile.
You can download a shapefile containing a set of urban area polygons from https://geospatialpython.googlecode.com/files/MS_UrbanAnC10.zip.
Extract this file to a directory named ms
in your qgis_data
directory.
We will classify each urban area by population size using a graduated symbol, as follows:
QColor
object to build our color range.from PyQt4.QtGui import QColor
lyr = QgsVectorLayer("/qgis_data/ms/MS_UrbanAnC10.shp", "Urban Areas", "ogr")
population = ( ("Village", 0.0, 3159.0, "cyan"), ("Small town", 3160.0, 4388.0, "blue"), ("Town", 43889.0, 6105.0, "green"), ("City", 6106.0, 10481.0, "yellow"), ("Large City", 10482.0, 27165, "orange"), ("Metropolis", 27165.0, 1060061.0, "red"))
ranges = []
for label, lower, upper, color in population: sym = QgsSymbolV2.defaultSymbol(lyr.geometryType()) sym.setColor(QColor(color)) rng = QgsRendererRangeV2(lower, upper, sym, label) ranges.append(rng)
field = "POP"
renderer = QgsGraduatedSymbolRendererV2(field, ranges)
lyr.setRendererV2(renderer)
QgsMapLayerRegistry.instance().addMapLayer(lyr)
The approach to using a graduated symbol for a vector layer is very similar to the color ramp shader for a raster layer. You can have as many ranges as you'd like by extending the Python tuple that is used to build the ranges. Of course, you can also build your own algorithms by programmatically examining the data fields first and then dividing up the values in equal intervals or some other scheme.