Adding a legend to the map

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.

Getting ready

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.

How to do it...

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:

  1. First, we will need to load the Qt and QGIS GUI libraries followed by the MapComposer library:
    from PyQt4.QtCore import *
    from PyQt4.QtGui import *
    from qgis.core import *
    from qgis.gui import *
    import MapComposer
    
  2. Next, we will load the shapefile as a layer and create the map composition with the 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)
    
  3. Now, we initialize the legend object:
    qc.legend = QgsComposerLegend(qc.c)
    
  4. We now tell the legend which layer set we want to use:
    qc.legend.model().setLayerSet(qc.qmr.layerSet())
    
  5. Then, we set the legend's position to the left-hand side of the map and add it to the composition:
    qc.legend.setItemPosition(5, qc.y)
    qc.c.addItem(qc.legend)
    
  6. Finally, we output the composition to the map:
    qc.output("/qgis_data/map.jpg", "jpg")
    

How it works...

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.

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

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