Creating a graduated vector layer symbol renderer

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.

Getting ready

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.

How to do it...

We will classify each urban area by population size using a graduated symbol, as follows:

  1. First, we import the QColor object to build our color range.
    from PyQt4.QtGui import QColor
    
  2. Next, we load our polygon shapefile as a vector layer:
    lyr = QgsVectorLayer("/qgis_data/ms/MS_UrbanAnC10.shp", "Urban Areas", "ogr")
    
  3. Now, we build some nested Python tuples that define the symbol graduation. Each item in the tuple contains a range label, range start value, range end value, and a color name, as shown here:
    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"))
    
  4. Then, we establish a Python list to hold our QGIS renderer objects:
    ranges = []
    
  5. Next, we loop through our range list, build the QGIS symbols, and add them to the renderer list:
    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)
    
  6. Now, reference the field name containing the population values in the shapefile attributes:
    field = "POP"
    
  7. Then, we create the renderer:
    renderer = QgsGraduatedSymbolRendererV2(field, ranges)
    
  8. We assign the renderer to the layer:
    lyr.setRendererV2(renderer)
    
  9. Finally, we add the map to the layer:
    QgsMapLayerRegistry.instance().addMapLayer(lyr)
    

How it works...

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset