Layer Symbols: QGIS Python Programming CookBook



Learn how to symbolize layers using SVG and pie charts in QGIS using Python from this section as part of this preview chapter, Creating Dynamic Maps from QGIS Python Programming CookBook. With 140 short, reusable recipes to automate geospatial processes in QGIS, the QGIS Python Programming CookBook teaches readers how to use Python and QGIS to create and transform data, produce appealing GIS visualizations, and build complex map layouts.

Using SVG for Layer Symbols

Scalable Vector Graphics orSVG are an XML standard defining vector graphics which can be scaled at any resolution. QGIS can use SVG files as markers for points. In this recipe, we’ll use python to apply one of the SVG symbols included with QGIS to a point layer.

Getting ready

For this recipe, download the following zipped point shapefile layer:

Free weekly newsletter

Fill out your e-mail address to receive our newsletter!

Extract it to your qgis_data directory.

How to do it…

In the following steps, we’ll load the vector layer, build a symbol layer and renderer, and add it to the layer.

  1. First we’ll define the path to the shapefile:

src = “/Users/joellawhead/qgis_data/NYC_MUSEUMS_GEO/NYC_MUSEUMS_GEO.shp”

  1. Next well load the layer:

lyr = QgsVectorLayer(src, “Museums”, “ogr”)

  1. Now we define the properties of the symbol including the location of the SVG file as a python dictionary:

svgStyle = {}

svgStyle[‘fill’] = ‘#0000ff’

svgStyle[‘name’] = ‘landmark/tourism=museum.svg’

svgStyle[‘outline’] = ‘#000000’

svgStyle[‘outline-width’] = ‘6.8’

svgStyle[‘size’] = ‘6’

  1. Then we create an SVG symbol layer:

symLyr1 = QgsSvgMarkerSymbolLayerV2.create(svgStyle)

  1. Now we change the layer renderer’s default symbol layer:

lyr.rendererV2().symbols()[0].changeSymbolLayer(0, symLyr1)

  1. Finally we add the layer to the map to view the SVG symbol:


How it works…

The default SVG layers are stored in the QGIS application directory. There are numerous graphics available covering many common uses. You can also add your own graphics as well. The following map image shows the recipe output.


Using Pie Charts for Symbols

QGIS has the ability to use dynamic pie charts as symbols describing 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:

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 with many more options.

  1. First we import the PyQt GUI library:
  2. from PyQt4.QtGui import *
  3. Then we load the layer:

lyr = QgsVectorLayer(“/Users/joellawhead/qgis_data/ms/County10PopnHou.shp”, “Population”, “ogr”)

  1. 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’]

  1. Now we set up a list of corresponding colors for each category:

colors = [‘#3727fa’,’#01daae’,’#f849a6′,’#268605′,’#6810ff’,’#453990′,’#630f2f’,’#07dd45′]

  1. Next we convert the hex color values to QColor objects:

qcolors = []

for c in colors:


  1. Now we reference the map canvas:

canvas = iface.mapCanvas()

  1. Then we create a pie diagram object:

diagram = QgsPieDiagram()

  1. Then we create a diagram settings object:

ds = QgsDiagramSettings()

  1. Now we define all of 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

  1. Now we can create our diagram renderer:

dr = QgsLinearlyInterpolatedDiagramRenderer()

  1. We must set a few size parameters for our diagrams:


dr.setLowerSize(QSizeF(0.0, 0.0))




  1. Then we can add our diagram to the renderer:


  1. And then we add the renderer to the layer:


  1. 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


  1. In QGIS 2.6, The diagram renderer is tied to the new PAL labeling engine so we need to activate that engine:

label = QgsPalLayerSettings()


label.enabled = True


  1. Next we delete any cached images that are rendered and force the layer to repaint:

ifhasattr(lyr, “setCacheImage”): lyr.setCacheImage(None)


  1. Finally, add our diagram layer to the map:


How it works…

The basics of pie chart diagram symbols are straight forward and work similar to other types of symbols and renderers. However it gets a little confusing in that we must 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.


There’s more…

To learn more about what is possible with pie chart diagram symbols, you can experiment with this recipe in the ScriptRunner 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 well to the python API.

QGIS Python Programming CookBook

<– Previous: Scale and Layer Visibility     |     Next: OpenStreetMap Service –>

Photo of author
About the author