Using pie charts for symbols

QGIS has the ability to use dynamic pie charts as symbols describing the statistics in a given region. In this recipe, we'll use pie chart symbols on a polygon layer in QGIS.

Getting ready

For this recipe, download the following zipped shapefile and extract it to a directory named ms in your qgis_data directory from https://geospatialpython.googlecode.com/svn/County10PopnHou.zip.

How to do it...

As with other renderers, we will build a symbol layer, add it to a renderer, and display the layer on the map. The pie chart diagram renderers are more complex than other renderers but have many more options. Perform the following steps to create a pie chart map:

  1. First, we import the PyQt GUI library:
    from PyQt4.QtGui import *
    
  2. Then, we load the layer:
    lyr = QgsVectorLayer("/Users/joellawhead/qgis_data/ms/County10PopnHou.shp", "Population", "ogr")
    
  3. Next, we set up categories based on attribute names:
    categories = [u'PCT_WHT', u'PCT_BLK', u'PCT_AMIND', u'PCT_ASIAN', u'PCT_HAW', u'PCT_ORA', u'PCT_MR', u'PCT_HISP']
    
  4. Now, we set up a list of corresponding colors for each category:
    colors = ['#3727fa','#01daae','#f849a6','#268605','#6810ff','#453990','#630f2f','#07dd45']
    
  5. Next, we convert the hex color values to QColor objects:
    qcolors = []
    for c in colors:
      qcolors.append(QColor(c))
    
  6. Now, we reference the map canvas:
    canvas = iface.mapCanvas()
    
  7. Then, we create a pie diagram object:
    diagram = QgsPieDiagram()
    
  8. Then, we create a diagram settings object:
    ds = QgsDiagramSettings()
    
  9. Now, we define all the diagram settings that will be used for the renderer:
    ds.font = QFont("Helvetica", 12)
    ds.transparency = 0
    ds.categoryColors = qcolors
    ds.categoryAttributes = categories
    ds.size = QSizeF(100.0, 100.0)
    ds.sizeType = 0 
    ds.labelPlacementMethod = 1 
    ds.scaleByArea = True 
    ds.minimumSize = 0 
    ds.BackgroundColor = QColor(255,255,255,0)
    ds.PenColor = QColor("black") 
    ds.penWidth = 0
    
  10. Now, we can create our diagram renderer:
    dr = QgsLinearlyInterpolatedDiagramRenderer()
    
  11. We must set a few size parameters for our diagrams:
    dr.setLowerValue(0.0)
    dr.setLowerSize(QSizeF(0.0, 0.0))
    dr.setUpperValue(2000000)
    dr.setUpperSize(QSizeF(40,40))
    dr.setClassificationAttribute(6)
    
  12. Then, we can add our diagram to the renderer:
    dr.setDiagram(diagram)
    
  13. Next, we add the renderer to the layer:
    lyr.setDiagramRenderer(dr)
    
  14. Now, we apply some additional placement settings at the layer level:
    dls = QgsDiagramLayerSettings() 
    dls.dist = 0
    dls.priority = 0
    dls.xPosColumn = -1  
    dls.yPosColumn = -1
    dls.placement = 0 
    lyr.setDiagramLayerSettings(dls)
    
  15. In QGIS 2.6, the diagram renderer is tied to the new PAL labeling engine, so we need to activate this engine:
    label = QgsPalLayerSettings() 
    label.readFromLayer(lyr) 
    label.enabled = True 
    label.writeToLayer(lyr)
    
  16. Next, we delete any cached images that are rendered and force the layer to repaint:
    if hasattr(lyr, "setCacheImage"):
        lyr.setCacheImage(None)
        
    lyr.triggerRepaint()
    
  17. Finally, we add our diagram layer to the map:
    QgsMapLayerRegistry.instance().addMapLayer(lyr)
    

How it works...

The basics of pie chart diagram symbols are straightforward and work in a similar way to other types of symbols and renderers. However, it gets a little confusing as we need to apply settings at three different levels – the diagram level, the render level, and the layer level. It turns out they are actually quite complex. Most of the settings are poorly documented, if at all. Fortunately, most of them are self-explanatory. The following screenshot shows an example of the completed pie chart diagram map:

How it works...

There's more...

To learn more about what is possible with pie chart diagram symbols, you can experiment with this recipe in the Script Runner plugin, where you can change or remove settings and quickly re-render the map. You can also manually change the settings using the QGIS dialogs and then export the style to an XML file and see what settings are used. Most of them map to the Python API well.

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

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