Overview of this book

QGIS is a desktop geographic information system that facilitates data viewing, editing, and analysis. Paired with the most efficient scripting language—Python, we can write effective scripts that extend the core functionality of QGIS. Based on version QGIS 2.18, this book will teach you how to write Python code that works with spatial data to automate geoprocessing tasks in QGIS. It will cover topics such as querying and editing vector data and using raster data. You will also learn to create, edit, and optimize a vector layer for faster queries, reproject a vector layer, reduce the number of vertices in a vector layer without losing critical data, and convert a raster to a vector. Following this, you will work through recipes that will help you compose static maps, create heavily customized maps, and add specialized labels and annotations. As well as this, we’ll also share a few tips and tricks based on different aspects of QGIS.

Creating a dot density map

A dot density map uses point density to illustrate a field value within a polygon. We'll use this technique to illustrate population density in some US census bureau tracts.

You will need to download the census tract layer and extract it to a directory named `census` in your `qgis_data` directory from https://github.com/GeospatialPython/Learn/raw/master/GIS_CensusTract.zip.

How to do it...

We will load the census layer, create a memory layer, loop through the features in the census layer, calculate a random point within the feature for every 100 people, and finally add the point to the memory layer. To do this, we need to perform the following steps:

1. In the QGIS Python console, we'll import the `random` module:

```        import random
```
2. Next, we'll load the `census` layer:

```        src = "/qgis_data/qgis_data/census/GIS_CensusTract_poly.shp"
tractLyr = QgsVectorLayer(src, "Census Tracts", "ogr")
```
3. Then, we'll create our `memory` layer:

`        popLyr...`