A map legend decodes the symbology used in a thematic GIS map for the reader. Legends are tightly integrated into QGIS, and in this recipe, we'll add the default legend from the map to the print composition.
Download the shapefile for this map from https://geospatialpython.googlecode.com/svn/Mississippi.zip and extract it to your qgis_data
directory in a subdirectory named ms
.
As with the previous recipes in this chapter, we will use the MapComposer
library from https://geospatialpython.googlecode.com/svn/MapComposer.py to simplify the creation of the map composition.
Place the file in the .qgis2/python
directory within your home directory.
This recipe is as simple as creating the map, adding the automatically generated legend, and saving the output to an image. To do this, we need to perform the following steps:
from PyQt4.QtCore import * from PyQt4.QtGui import * from qgis.core import * from qgis.gui import * import MapComposer
MapComposer
library, passing it the map layer registry and map renderer:lyr = QgsVectorLayer("/qgis_data/ms/mississippi.shp", "Mississippi", "ogr") reg = QgsMapLayerRegistry.instance() reg.addMapLayer(lyr) mr = iface.mapCanvas().mapRenderer() qc = MapComposer.MapComposer(qmlr=reg, qmr=mr)
qc.legend = QgsComposerLegend(qc.c)
qc.legend.model().setLayerSet(qc.qmr.layerSet())
qc.legend.setItemPosition(5, qc.y) qc.c.addItem(qc.legend)
qc.output("/qgis_data/map.jpg", "jpg")
Adding a legend is quite simple. QGIS will carry over the styling that is autogenerated when the layer is loaded or manually set by the user. Of course, you can also save layer styling, which is loaded with the layer and used by the legend. However, if you're generating a composition in the background such as in a standalone application, for example, every aspect of the legend is customizable through the PyQGIS API.