9.4. Lesson: Supplementary Exercise

In this lesson, you will be guided through a complete GIS analysis in QGIS.


Lesson developed by Linfiniti and S Motala (Cape Peninsula University of Technology)

9.4.1. Problem Statement

You are tasked with finding areas in and around the Cape Peninsula that are a suitable habitat for a rare fynbos plant species. The extent of your area of investigation in the Cape Peninsula is: south of Melkbosstrand, west of Strand. Botanists have provided you with the following preferences exhibited by the species in question:

  • It grows on east facing slopes.

  • It grows on slopes with a gradient between 15% and 60%.

  • It grows in areas that have a total annual rainfall of > 1200 mm.

  • It will only be found at least 250 m away from any human settlement.

  • The area of vegetation in which it occurs should be at least 6000m2 in area.

As a volunteer for Cape Nature, you have agreed to search for the plant on the closest suitable piece of land to your house. Use your GIS skills to determine where you should go to look.

9.4.2. Solution Outline

The data for this exercise can be found in the exercise_data/more_analysis folder. You are going to find the candidate area that is closest to a house of your choice. The solution will involve:

  1. analysing the DEM to find the east facing slopes and the slopes with the correct gradients;

  2. analysing the rainfall raster to find the areas with the correct amount of rainfall;

  3. analysing the Zoning vector layer to find areas that are away from human settlement and are of the correct size.

9.4.3. Setting up the Map

  1. Click on the “CRS status” button in the extreme lower right corner of the screen. Under the CRS tab of the screen that appears, you will see the box Coordinate reference systems of the world.

  2. In this box, navigate to Projected Coordinate Systems ‣ Universal Transverse Mercator (UTM).

  3. Select the entry WGS 84 / UTM zone 33S (with the EPSG code 32733).

  4. Click OK. The map is now in the UTM33S coordinate reference system.

  5. Save the map by clicking on the Save Project As toolbar button, or use the File ‣ Save Project As… menu item.

  6. Save the map in a directory called Rasterprac that you should create somewhere on your computer. You will save whatever layers you create in this directory as well.

9.4.4. Loading Data into the Map

In order to process the data, you will need to load the necessary layers (street names, zones, rainfall, DEM) into the map canvas. For vectors…

  1. Click on the dataSourceManager Open Data Source Manager button and enable the addOgrLayer Vector tab in the dialog that appears, or use the Layer ‣ Add Layer ‣ addOgrLayer Add Vector Layer… menu item.

  2. Ensure that the File radio button is selected.

  3. Click on the button to browse for Vector dataset(s).

  4. In the dialog that appears, open the exercise_data/more_analysis/streets directory.

  5. Select the file Street_Names_UTM33S.shp.

  6. Click Open.

    The dialog closes and shows the original dialog, with the file path specified in the text field next to the Vector dataset(s) button. This allows you to ensure that the correct file is selected. It is also possible to enter the file path in this field manually, should you wish to do so.

  7. Click Add. The vector layer will load in your map. Its color is automatically assigned. It will be changed later.

  8. Rename the layer to Streets.

    1. Right-click on it in the Layers panel (by default, the pane along the left-hand side of the screen).

    2. Click Rename in the dialog that appears and rename it, pressing the Enter key when done.

  9. Repeat the vector adding process, but this time select the Generalised_Zoning_Dissolve_UTM33S.shp file in the Zoning directory.

  10. Rename it to Zoning. For rasters…

  1. Click on the dataSourceManager Open Data Source Manager button and enable the addRasterLayer Raster tab in the dialog that appears, or use the Layer ‣ Add Layer ‣ addRasterLayer Add Raster Layer… menu item.

  2. Ensure that the File radio button is selected.

  3. Navigate to the appropriate file, select it, and click Open.

  4. Do this for each of the two raster files. The files you want are DEM/reproject/DEM.tif and Rainfall/reprojected/rainfall.tif.

  5. Rename the rainfall raster to Rainfall (with an initial capital). Initially when you load them, the images will be gray rectangles. Don’t worry, this will be changed later.

  6. Save the map.

In order to properly see what’s going on, the symbology for the layers needs to be changed.

9.4.5. Changing the symbology of vector layers

  1. In the Layers panel, right-click on the Streets layer.

  2. Select Properties from the menu that appears.

  3. Switch to the Symbology tab in the dialog that appears.

  4. Click on the button labelled Change, with a square showing the current color of the Streets layer.

  5. Select a new color in the dialog that appears.

  6. Click OK.

  7. Click OK again in the Layer Properties dialog. This will change the color of the Streets layer.

  8. Follow a similar process for the Zoning layer and choose an appropriate color for it.

9.4.6. Changing the symbology of raster layers

Raster layer symbology is somewhat different.

  1. Open the Properties dialog for the Rainfall raster.

  2. Switch to the Symbology tab. You’ll notice that this dialog is very different from the version used for vector layers.

  3. Ensure that the button Use standard deviation is selected.

  4. Change the value in the associated box to 2.00 (it should be set to 0.00 by default).

  5. Under the heading Contrast enhancement, change the value of the Current dropdown list to Stretch to MinMax.

  6. Click OK. The “Rainfall” raster, if visible, should change colors, allowing you to see different brightness values for each pixel.

  7. Repeat this process for the DEM, but set the standard deviations used for stretching to 4.00.

9.4.7. Changing the layer order

  1. In the Layers panel, click and drag layers up and down to change the order they appear in on the map.

  2. Newer versions of QGIS may have a Control rendering order checkbox beneath the Layers panel. Ensure that it is checked.

Now that all the data is loaded and properly visible, the analysis can begin. It is best if the clipping operation is done first. This is so that no processing power is wasted on computing values in areas that aren’t going to be used anyway.

9.4.8. Find the Correct Districts

  1. Load the vector layer admin_boundaries/Western_Cape_UTM33S.shp into your map.

  2. Rename it to Districts.

  3. Right-click on the Districts layer in the Layers panel.

  4. In the menu that appears, select the Query… menu item. The Query Builder dialog appears.

You will now build a query to select only the following list of districts:

  • Bellville

  • Cape

  • Goodwood

  • Kuils River

  • Mitchells Plain

  • Simons Town and

  • Wynberg.

  1. In the Fields list, double-click on the NAME_2 field. It appears in the SQL where clause text field below.

  2. Click the = button; an = sign is added to the SQL query.

  3. Click the All button below the (currently empty) Values list. After a short delay, this will populate the Values list with the values of the selected field (NAME_2).

  4. Double-click the value Bellville in the Values list. As before, this will be added to the SQL query.

In order to select more than one district, you’ll need to use the OR boolean operator.

  1. Click the OR button and it will be added to the SQL query.

  2. Using a process similar to the above, add the following to the existing SQL query:

    "NAME_2" = 'Cape'
  3. Add another OR operator, then work your way through the list of districts above in a similar fashion.

    The final query should be

    "NAME_2" = 'Bellville' OR "NAME_2" = 'Cape' OR "NAME_2" = 'Goodwood' OR
    "NAME_2" = 'Kuils River' OR "NAME_2" = 'Mitchells Plain' OR "NAME_2" =
    'Simons Town' OR "NAME_2" = 'Wynberg'
  4. Click OK. The districts shown in your map are now limited to those in the list above.

9.4.9. Clip the Rasters

Now that you have an area of interest, you can clip the rasters to this area.

  1. Ensure that the only layers that are visible are the DEM, Rainfall and Districts layers.

  2. Districts must be on top so that they are visible.

  3. Open the clipping dialog by selecting the menu item Raster ‣ Extraction ‣ Clipper.

  4. In the Input file (raster) dropdown list, select the DEM layer.

  5. Specify an output location in the Output file text field by clicking the Select… button.

  6. Navigate to your Rasterprac directory.

  7. Enter a file name.

  8. Save the file. Leave the No data value checkbox unchecked.

  9. Use the Extent clipping mode by ensuring the correct radio button is selected.

  10. Click and drag an area in the canvas, so that the area which includes the districts is selected.

  11. Check the Open output file after running algorithm box.

  12. Click Run.

  13. After the clipping operation is completed, DO NOT CLOSE the Clipper dialog. (Doing so would cause you to lose the clipping area that you have already defined.)

  14. Select the Rainfall raster in the Input file (raster) dropdown list and choose a different output file name.

  15. Do not change any other options. Do not alter the existing clipping area which you drew previously. Leave everything the same and click Run.

  16. After the second clipping operation has completed, you may close the Clipper dialog.

  17. Save the map.

9.4.10. Clean up the map

  1. Remove the original Rainfall and DEM layers from the Layers panel:

  2. Right-click on these layers and select Remove.


    This will not remove the data from your storage device, it will merely take it out of your map.

  3. Deactivate the labels on the Streets layer:

    1. Click the Labeling button.

    2. Uncheck the Label this layer with box.

    3. Click OK.

  4. Show all the Streets again:

    1. Right-click on the layer in the Layers panel.

    2. Select Query.

    3. In the Query dialog that appears, click the Clear button, then click OK.

    4. Wait while the data is loaded. All the streets will now be visible.

  5. Change the raster symbology as before (see Changing the symbology of raster layers).

  6. Save the map.

  7. You can now hide the vector layers by unchecking the box next to them in the Layers panel. This will make the map render faster and will save you some time.

In order to create the hillshade, you will need to use an algorithm that was written for this purpose.

9.4.11. Create the hillshade

  1. In the Layers panel, ensure that the DEM is the active layer (i.e., it is highlighted by having been clicked on).

  2. Click on the Raster ‣ Analysis ‣ Hillshade menu item to open the Hillshade dialog.

  3. Specify an appropriate location for the output layer and call it hillshade.

  4. Check the Open output file after running algorithm box.

  5. Click Run.

  6. Wait for it to finish processing.

The new hillshade layer has appeared in your Layers list.

  1. Right-click on the hillshade layer in your Layers list and bring up the Properties dialog.

  2. Click on the Transparency tab and set the transparency slider to 80%.

  3. Click Run on the dialog.

  4. Note the effect when the transparent hillshade is superimposed over the clipped DEM.

9.4.12. Slope

  1. Click on the menu item Raster ‣ Terrain analysis.

  2. Select the Slope analysis type, with the clipped DEM as the input layer.

  3. Specify an appropriate file name and location for output purposes.

  4. Check the Open output file after running algorithm box.

  5. Click Run.

The slope image has been calculated and added to the map. However, as usual it is just a gray rectangle. To properly see what’s going on, change the symbology as follows.

  1. Open the layer Properties dialog (as usual, via the right-click menu of the layer).

  2. Click on the Symbology tab.

  3. Where it says Grayscale (in the Color map dropdown menu), change it to Pseudocolor.

  4. Ensure that the Use standard deviation radio button is selected.

9.4.13. Aspect

Use the same approach as for calculating the slope, but select Aspect in the initial dialog box.

Remember to save the map periodically.

9.4.14. Reclassifying rasters

  1. Click the menu item Raster ‣ Raster calculator.

  2. Specify your Rasterprac directory as the location for the output layer.

  3. Ensure that the Open output file after running algorithm box is selected.

In the Raster bands list on the left, you will see all the raster layers in your Layers panel. If your Slope layer is called slope, it will be listed as slope@1.

The slope needs to be between 15 and 60 degrees. Everything less than 15 or greater than 60 must therefore be excluded.

  1. Using the list items and buttons in the interface, build the following expression:

    ((slope@1 < 15) OR (slope@1 > 60)) = 0
  2. Set the Output layer field to an appropriate location and file name.

  3. Click Run.

Now find the correct aspect (east-facing: between 45 and 135 degrees) using the same approach.

  1. Build the following expression:

    ((aspect@1 < 45) OR (aspect@1 > 135)) = 0
  2. Find the correct rainfall (greater than 1200mm) the same way. Build the following expression:

    (rainfall@1 < 1200) = 0

Having reclassified all the rasters, you will now see them displayed as gray rectangles in your map (assuming that they have been added to the map correctly). To properly display raster data with only two classes (1 and 0, meaning true or false), you will need to change their symbology.

9.4.15. Setting the style for the reclassified layers

  1. Open the Symbology tab in the layer’s Properties dialog as usual.

  2. Under the heading Load min / max values from band, select the Actual (slower) radio button.

  3. Click the Load button.

The Custom min / max values fields should now populate with 0 and 1, respectively. (If they do not, then there was a mistake with your reclassification of the data, and you will need to go over that part again.)

  1. Under the heading Contrast enhancement, set the Current dropdown list to Stretch To MinMax.

  2. Click OK.

  3. Do this for all three reclassified rasters, and remember to save your work!

The only criterion that remains is that the area must be 250m away from urban areas. We will satisfy this requirement by ensuring that the areas we compute are 250m or more from the edge of a rural area. Hence, we need to find all rural areas first.

9.4.16. Finding rural areas

  1. Hide all layers in the Layers panel.

  2. Unhide the Zoning vector layer.

  3. Right-click on it and bring up the Query dialog.

  4. Build the following query:

    "Gen_Zoning" = 'Rural'

    See the earlier instructions for building the Streets query if you get stuck.

  5. When you’re done, close the Query dialog.

You should see a collection of polygons from the Zoning layer. You will need to save these to a new layer file.

  1. On the right-click menu for Zoning, select Save as….

  2. Save your layer under the Zoning directory.

  3. Name the output file rural.shp.

  4. Click OK.

  5. Add the layer to your map.

  6. Click the menu item Vector ‣ Geoprocessing Tools ‣ Dissolve.

  7. Select the rural layer as your input vector layer, while leaving the Use only selected features box unchecked.

  8. Leave empty the Dissolve field(s) option to combine all selected features in a single one.

  9. Save your layer under the Zoning directory.

  10. Check the Open output file after running algorithm box.

  11. Click Run.

  12. Close the Dissolve dialog.

  13. Remove the rural and Zoning layers.

  14. Save the map.

Now you need to exclude the areas that are within 250m from the edge of the rural areas. Do this by creating a negative buffer, as explained below.

9.4.17. Creating a negative buffer

  1. Click the menu item Vector ‣ Geoprocessing Tools ‣ Buffer(s).

  2. In the dialog that appears, select the rural_dissolve layer as your input vector layer (Use only selected features should not be checked).

  3. Select the Buffer distance button and enter the value -250 into the associated field; the negative value means that the buffer must be an internal buffer.

  4. Check the Dissolve buffer results box.

  5. Set the output file to the same directory as the other rural vector files.

  6. Name the output file rural_buffer.shp.

  7. Click Save.

  8. Click OK and wait for the processing to complete.

  9. Select Yes on the dialog that appears.

  10. Close the Buffer dialog.

  11. Remove the rural_dissolve layer.

  12. Save the map.

In order to incorporate the rural zones into the same analysis with the three existing rasters, it will need to be rasterized as well. But in order for the rasters to be compatible for analysis, they will need to be the same size. Therefore, before you can rasterize, you’ll need to clip the vector to the same area as the three rasters. A vector can only be clipped by another vector, so you will first need to create a bounding box polygon the same size as the rasters.

9.4.18. Creating a bounding box vector

  1. Click on the menu item Layer ‣ New ‣ New Shapefile Layer….

  2. Under the Type heading, select the Polygon button.

  3. Click Specify CRS and set the coordinate reference system WGS 84 / UTM zone 33S : EPSG:32733.

  4. Click OK.

  5. Click OK on the New Vector Layer dialog as well.

  6. Save the vector in the Zoning directory.

  7. Name the output file bbox.shp.

  8. Hide all layers except the new bbox layer and one of the reclassified rasters.

  9. Ensure that the bbox layer is highlighted in the Layers panel.

  10. Navigate to the View > Toolbars menu item and ensure that Digitizing is selected. You should then see a toolbar icon with a pencil or koki on it. This is the Toggle editing button.

  11. Click the Toggle editing button to enter edit mode. This allows you to edit a vector layer.

  12. Click the Add feature button, which should be nearby the Toggle editing button. It may be hidden behind a double arrow button; if so, click the double arrows to show the Digitizing toolbar’s hidden buttons.

  13. With the Add feature tool activated, left-click on the corners of the raster. You may need to zoom in with the mouse wheel to ensure that it is accurate. To pan across the map in this mode, click and drag in the map with the middle mouse button or mouse wheel.

  14. For the fourth and final point, right-click to finalize the shape.

  15. Enter any arbitrary number for the shape ID.

  16. Click OK.

  17. Click the Save edits button.

  18. Click the Toggle editing button to stop your editing session.

  19. Save the map.

Now that you have a bounding box, you can use it to clip the rural buffer layer.

9.4.19. Clipping a vector layer

  1. Ensure that only the bbox and rural_buffer layers are visible, with the latter on top.

  2. Click the menu item Vector > Geoprocessing Tools > Clip.

  3. In the dialog that appears, set the input vector layer to rural_buffer and the clip layer to bbox, with both Use only selected features boxes unchecked.

  4. Put the output file under the Zoning directory.

  5. Name the output file rural_clipped.

  6. Click OK.

  7. When prompted to add the layer to the TOC, click Yes.

  8. Close the dialog.

  9. Compare the three vectors and see the results for yourself.

  10. Remove the bbox and rural_buffer layers, then save your map.

Now it’s ready to be rasterized.

9.4.20. Rasterizing a vector layer

You’ll need to specify a pixel size for a new raster that you create, so first you’ll need to know the size of one of your existing rasters.

  1. Open the Properties dialog of any of the three existing rasters.

  2. Switch to the Metadata tab.

  3. Make a note of the X and Y values under the heading Dimensions in the Metadata table.

  4. Close the Properties dialog.

  5. Click on the Raster ‣ Conversion ‣ Rasterize menu item. You may receive a warning about a dataset being unsupported. Click it away and ignore it.

  6. Select rural_clipped as your input layer.

  7. Set an output file location inside the Zoning directory.

  8. Name the output file rural_raster.tif.

  9. Check the New size box and enter the X and Y values you made a note of earlier.

  10. Check the Load into canvas box.

  11. Click the pencil icon next to the text field which shows the command that will be run. At the end of the existing text, add a space and then the text -burn 1. This tells the Rasterize function to “burn” the existing vector into the new raster and give the areas covered by the vector the new value of 1 (as opposed to the rest of the image, which will automatically be 0).

  12. Click OK.

  13. The new raster should show up in your map once it has been computed.

  14. The new raster will look like a grey rectangle – you may change the display style as you did for the reclassified rasters.

  15. Save your map.

Now that you have all four criteria each in a separate raster, you need to combine them to see which areas satisfy all the criteria. To do so, the rasters will be multiplied with each other. When this happens, all overlapping pixels with a value of 1 will retain the value of 1, but if a pixel has the value of 0 in any of the four rasters, then it will be 0 in the result. In this way, the result will contain only the overlapping areas.

9.4.21. Combining rasters

  1. Click the Raster ‣ Raster calculator menu item.

  2. Build the following expression (with the appropriate names for your layers, depending on what you called them):

    [Rural raster] * [Reclassified aspect] * [Reclassified slope] *
    [Reclassified rainfall]
  3. Set the output location to the Rasterprac directory.

  4. Name the output raster cross_product.tif.

  5. Ensure that the Open output file after running algorithm box is checked.

  6. Click Run.

  7. Change the symbology of the new raster in the same way as you set the style for the other reclassified rasters. The new raster now properly displays the areas where all the criteria are satisfied.

To get the final result, you need to select the areas that are greater than 6000m^2. However, computing these areas accurately is only possible for a vector layer, so you will need to vectorize the raster.

9.4.22. Vectorizing the raster

  1. Click on the menu item Raster ‣ Conversion ‣ Polygonize.

  2. Select the cross_product.tif raster.

  3. Set the output location to Rasterprac.

  4. Name the file candidate_areas.shp.

  5. Ensure that Open output file after running algorithm is checked.

  6. Click Run.

  7. Close the dialog when processing is complete.

All areas of the raster have been vectorized, so you need to select only the areas that have a value of 1.

  1. Open the Query dialog for the new vector.

  2. Build this query:

    "DN" = 1
  3. Click OK.

  4. Create a new vector file from the results by saving the candidate_areas vector after the query is complete (and only the areas with a value of 1 are visible). Use the Save as… function in the layer’s right-click menu for this.

  5. Save the file in the Rasterprac directory.

  6. Name the file candidate_areas_only.shp.

  7. Save your map.

9.4.23. Calculating the area for each polygon

  1. Open the new vector layer’s right-click menu.

  2. Select Open attribute table.

  3. Click the Toggle editing mode button along the bottom of the table, or press Ctrl+E.

  4. Click the Open field calculator button along the bottom of the table, or press Ctrl+I.

  5. Under the New field heading in the dialog that appears, enter the field name area. The output field type should be an integer, and the field width should be 10.

  6. In Field calculator expression, type:


    This means that the field calculator will calculate the area of each polygon in the vector layer and will then populate a new integer column (called area) with the computed value.

  7. Click OK.

  8. Do the same thing for another new field called id. In Field calculator expression, type:


    This ensures that each polygon has a unique ID for identification purposes.

  9. Click Toggle editing mode again, and save your edits if prompted to do so.

9.4.24. Selecting areas of a given size

Now that the areas are known:

  1. Build a query (as usual) to select only the polygons larger than 6000m^2. The query is:

    "area" > 6000
  2. Save the selection as a new vector layer called solution.shp.

You now have your solution areas, from which you will pick the one nearest to your house.

9.4.25. Digitize your house

  1. Create a new vector layer as before, but this time, select the Type value as being a Point.

  2. Ensure that it is in the correct CRS!

  3. Name the new layer house.shp.

  4. Finish creating the new layer.

  5. Enter edit mode (while the new layer is selected).

  6. Click the point where your house or other current place of residence is, using the streets as a guide. You might have to open other layers to help you find your house. If you don’t live anywhere nearby, just click somewhere among the streets where a house could conceivably be.

  7. Enter any arbitrary number for the shape ID.

  8. Click OK.

  9. Save your edits and exit edit mode.

  10. Save the map.

You will need to find the centroids (“centers of mass”) for the solution area polygons in order to decide which is closest to your house.

9.4.26. Calculate polygon centroids

  1. Click on the Vector ‣ Geometry Tools ‣ Centroids menu item.

  2. Specify the input layer as solution.shp.

  3. Provide the output location as Rasterprac.

  4. Call the destination file solution_centroids.shp.

  5. Check checkbox Open output file after running algorithm to add the result to the TOC (Layers panel).

  6. Click Run and close the dialog.

  7. Drag the new layer to the top of the layer order so that you can see it.

9.4.27. Calculate which centroid is closest to your house

  1. Click on the menu item Vector ‣ Analysis Tools ‣ Distance matrix.

  2. The input layer should be your house, and the target layer solution_centroids. Both of these should use the id field as their unique ID field.

  3. The output matrix type should be linear.

  4. Set an appropriate output location and name.

  5. Click OK.

  6. Open the file in a text editor (or import it into a spreadsheet). Note which target ID is associated with the shortest Distance. There may be more than one at the same distance.

  7. Build a query in QGIS to select only the solution areas closest to your house (selecting it using the id field).

This is the final answer to the research question.

For your submission, include the semi-transparent hillshade layer over an appealing raster of your choice (such as the DEM or the slope raster, for example). Also include the polygon of the closest solution area(s), as well as your house. Follow all the best practices for cartography in creating your output map.