blogs | next

tmap: quick and easy thematic mapping in R

In this tutorial we are going to have a look at a very quick and very easy way to create a choropleth map with the Thematic Maps package tmap in R. This package is created by Martijn Tennekes.

You can recreate the map above, using only a few lines of code.

As input for this exercise you will use a shapefile with municipal data to be downloaded from the website of the French Institut national de l’information géographique et forestière (IGN). On this page you will find the file GEOFLA® 2015 Communes France Métropolitaine.

Download and unzipg this file (e.g. using 7-Zip). Browse down the many subfolders in this archive until you find the shapefile COMMUNE.SHP (together with it’s corresponding *.DBF, *.LYR, *.PRJ and *.SHX files). Copy those 5 files to the \Data subdirectory of your R working directory.

You will need the two packages below. If necessary you should install them first, using install.packages().

## Warning: multiple methods tables found for 'overlay'
## Warning: replacing previous import by 'sp::overlay' when loading 'tmap'
## Loading required package: sp
## rgdal: version: 1.0-7, (SVN revision 559)
##  Geospatial Data Abstraction Library extensions to R successfully loaded
##  Loaded GDAL runtime: GDAL 1.11.2, released 2015/02/10
##  Path to GDAL shared files: C:/Program Files/R/R-3.2.2/library/rgdal/gdal
##  GDAL does not use iconv for recoding strings.
##  Loaded PROJ.4 runtime: Rel. 4.9.1, 04 March 2015, [PJ_VERSION: 491]
##  Path to PROJ.4 shared files: C:/Program Files/R/R-3.2.2/library/rgdal/proj
##  Linking to sp version: 1.2-0

Now load your data:

FR_Communes_2015 <- readOGR("Data", "COMMUNE")
## OGR data source with driver: ESRI Shapefile 
## Source: "Data", layer: "COMMUNE"
## with 36571 features
## It has 18 fields

Yes, as you can see, there are quite some municipalities in France.

You might want to have a quick look at the data by plotting them:


When using RStudio you can have a look at the attribute data using the Data Viewer:


There are 18 columns with attribute data, but no column with the population density. You do have POPULATION and SUPERFICIE (i.e. area), in hectares. To get the area in square kilometers you have to divide it by 100. Create a new column DENS_POP using this command:

FR_Communes_2015$DENS_POP <- round((FR_Communes_2015$POPULATION / (FR_Communes_2015$SUPERFICIE / 100)))

Now create your thematic map. After playing with the different options we came up with the code below, creating the thematic map at the top of this page:

tm_shape(FR_Communes_2015) +
tm_fill("DENS_POP", style="kmeans", n=10, title="Inhabitants/km2") +
tm_credits("data from", position = c("center", "bottom")) +
tm_layout("Population Density\nFrance, 2015", bg.color="lightgray", legend.title.size=.8)

Nice, isn’t it? (The one little thing missing here is superscript in the legend title: we did not yet find a way to plot km2, so we used km2 instead…)

Egge-Jan Pollé