A scale bar is one of the most important elements of a map composition, as it defines the scale of the map to determine the ground distance on the map. QGIS composer allows you to create several different types of scale bars from a simple text scale ratio to a graphical, double scale bar with two measurement systems. In this recipe, we'll create a scale bar that measures in kilometres.
You will need to download the following zipped shapefile and extract it to your qgis_data
directory, to a subdirectory named ms
:
https://geospatialpython.googlecode.com/svn/mississippi.zip
In addition to the shapefile, you will also need the MapComposer
class. This class encapsulates the boilerplate composer code in a reusable way to make adding other elements easier. You can download it from https://geospatialpython.googlecode.com/svn/MapComposer.py.
This file must be accessible from the QGIS Python console; ensure that it is in the Python path directory. Place the file in the .qgis2/python
directory within your home directory.
For the scale bar to display correctly, you must ensure that QGIS is set to automatically reproject data on the fly. In QGIS, go to the Settings menu and select Options. In the Options dialog, select the CRS panel. In the Default CRS for new projects section, check the Enable 'on the fly' reprojection by default radio button. Click on the OK button to confirm the setting.
First, we will generate the map, then we'll generate the composition, and finally we'll create the scale bar and place it in the lower-right corner of the map. 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
lyr = QgsVectorLayer("/Users/joellawhead/qgis_data/ms/mmississippi.shp", "Mississippi", "ogr") reg = QgsMapLayerRegistry.instance() reg.addMapLayer(lyr) mr = iface.mapCanvas().mapRenderer()
MapComposer
object using the layer registry and map renderer:qc = MapComposer.MapComposer(qmlr=reg, qmr=mr)
qc.scalebar = QgsComposerScaleBar(qc.c)
qc.scalebar.setStyle('Single Box')
qc.scalebar.setComposerMap(qc.composerMap) qc.scalebar.applyDefaultSize()
sbw = qc.scalebar.rect().width() sbh = qc.scalebar.rect().height() mcw = qc.composerMap.rect().width() mch = qc.composerMap.rect().height() sbx = qc.x + (mcw - sbw) sby = qc.y + mch
qc.scalebar.setItemPosition(sbx, sby) qc.c.addItem(qc.scalebar)
qc.output("/Users/joellawhead/qgis_data/map.jpg", "jpg")
The scale bar will display in kilometres if the map projection is set correctly, which is why it is important to have automatic reprojection enabled in the QGIS settings. The location of the scale bar within the composition is not important, as long as the composerMap
object is applied to it.