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.
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.
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:
from PyQt4.QtGui import *
lyr = QgsVectorLayer("/Users/joellawhead/qgis_data/ms/County10PopnHou.shp", "Population", "ogr")
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']
colors = ['#3727fa','#01daae','#f849a6','#268605','#6810ff','#453990','#630f2f','#07dd45']
QColor
objects:qcolors = [] for c in colors: qcolors.append(QColor(c))
canvas = iface.mapCanvas()
diagram = QgsPieDiagram()
ds = QgsDiagramSettings()
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
dr = QgsLinearlyInterpolatedDiagramRenderer()
dr.setLowerValue(0.0) dr.setLowerSize(QSizeF(0.0, 0.0)) dr.setUpperValue(2000000) dr.setUpperSize(QSizeF(40,40)) dr.setClassificationAttribute(6)
dr.setDiagram(diagram)
lyr.setDiagramRenderer(dr)
dls = QgsDiagramLayerSettings() dls.dist = 0 dls.priority = 0 dls.xPosColumn = -1 dls.yPosColumn = -1 dls.placement = 0 lyr.setDiagramLayerSettings(dls)
label = QgsPalLayerSettings() label.readFromLayer(lyr) label.enabled = True label.writeToLayer(lyr)
if hasattr(lyr, "setCacheImage"): lyr.setCacheImage(None) lyr.triggerRepaint()
QgsMapLayerRegistry.instance().addMapLayer(lyr)
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:
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.