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:
https://geospatialpython.googlecode.com/files/NYC_MUSEUMS_GEO.zip
Free weekly newsletter
Fill out your e-mail address to receive our newsletter!
By entering your email address you agree to receive our newsletter and agree with our privacy policy.
You may unsubscribe at any time.
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.
- First we’ll define the path to the shapefile:
src = “/Users/joellawhead/qgis_data/NYC_MUSEUMS_GEO/NYC_MUSEUMS_GEO.shp”
- Next well load the layer:
lyr = QgsVectorLayer(src, “Museums”, “ogr”)
- 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’
- Then we create an SVG symbol layer:
symLyr1 = QgsSvgMarkerSymbolLayerV2.create(svgStyle)
- Now we change the layer renderer’s default symbol layer:
lyr.rendererV2().symbols()[0].changeSymbolLayer(0, symLyr1)
- Finally we add the layer to the map to view the SVG symbol:
QgsMapLayerRegistry.instance().addMapLayer(lyr)
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:
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 with many more options.
- First we import the PyQt GUI library:
- from PyQt4.QtGui import *
- Then we load the layer:
lyr = QgsVectorLayer(“/Users/joellawhead/qgis_data/ms/County10PopnHou.shp”, “Population”, “ogr”)
- 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’]
- Now we set up a list of corresponding colors for each category:
colors = [‘#3727fa’,’#01daae’,’#f849a6′,’#268605′,’#6810ff’,’#453990′,’#630f2f’,’#07dd45′]
- Next we convert the hex color values to QColor objects:
qcolors = []
for c in colors:
qcolors.append(QColor(c))
- Now we reference the map canvas:
canvas = iface.mapCanvas()
- Then we create a pie diagram object:
diagram = QgsPieDiagram()
- Then we create a diagram settings object:
ds = QgsDiagramSettings()
- 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
- Now we can create our diagram renderer:
dr = QgsLinearlyInterpolatedDiagramRenderer()
- 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)
- Then we can add our diagram to the renderer:
dr.setDiagram(diagram)
- And then we add the renderer to the layer:
lyr.setDiagramRenderer(dr)
- 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)
- 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.readFromLayer(lyr)
label.enabled = True
label.writeToLayer(lyr)
- Next we delete any cached images that are rendered and force the layer to repaint:
ifhasattr(lyr, “setCacheImage”): lyr.setCacheImage(None)
lyr.triggerRepaint()
- Finally, add our diagram layer to the map:
QgsMapLayerRegistry.instance().addMapLayer(lyr)
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 –>