Creating a categorized vector layer symbol

A categorized vector layer symbol allows you to create distinct categories with colors and labels for unique features. This approach is typically used for datasets with a limited number of unique types of features. In this recipe, we'll categorize a vector layer into three different categories.

Getting ready

For this recipe, we'll use a land use shapefile, which you can download from https://geospatialpython.googlecode.com/svn/landuse_shp.zip.

Extract it to a directory named hancock in your qgis_data directory.

How to do it...

We will load the vector layer, create three categories of land use, and render them as categorized symbols. To do this, we need to perform the following steps:

  1. First, we need to import the QColor object for our category colors:
    from PyQt4.QtGui import QColor
    
  2. Then, we load the vector layer:
    lyr = QgsVectorLayer("Users/joellawhead/qgis_data/hancock/landuse.shp", "Land Use", "ogr")
    
  3. Next, we'll create our three land use categories using a Python dictionary with a field value as the key, color name, and label:
    landuse = {
      "0":("yellow", "Developed"),
      "1":("darkcyan", "Water"),
      "2":("green", "Land")}
    
  4. Now, we can build our categorized renderer items:
    categories = []
    for terrain, (color, label) in landuse.items():
      sym = QgsSymbolV2.defaultSymbol(lyr.geometryType())
      sym.setColor(QColor(color))
      category = QgsRendererCategoryV2(terrain, sym, label)
      categories.append(category)
    
  5. We name the field containing the land use value:
    field = "DN"
    
  6. Next, we build the renderer:
    renderer = QgsCategorizedSymbolRendererV2(field, categories)
    
  7. We add the renderer to the layer:
    lyr.setRendererV2(renderer)
    
  8. Finally, we add the categorized layer to the map:
    QgsMapLayerRegistry.instance().addMapLayer(lyr)
    

How it works...

There are only slight differences in the configurations of the various types of renderers in QGIS. Setting them up by first defining the properties of the renderer using native Python objects makes your code easier to read and ultimately manage. The following map image illustrates the categorized symbol in this recipe:

How it works...
..................Content has been hidden....................

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