Get startedGet started for free

Introduction to tmap

1. Introduction to tmap

We'll be using the tmap package throughout the rest of the course to visualize our spatial data.

2. tmap displays spatial data

It shares a similar philosophy and syntax to ggplot2, so you should find it quite intuitive. Like ggplot2, in tmap, a plot is built up in layers. However, ggplot2 is designed for easy of visualization of tidy data and expects data stored in data frames, whereas tmap is designed for visualizing spatial data and it expects data to be stored in a spatial object. Each layer consists of a type of graphical representation and a mapping from visual properties to variables.

3. Building a plot in layers

Let's take a look at a simple plot. We'll use the Europe data available as part of the tmap package, Europe is a SpatialPolygonsDataFrame of the countries in Europe along with some basic demographic information on each country. We start with a tm_shape call, this acts in a similar way to the ggplot call, specifying the data but not actually displaying anything. We can then add a layer, in this case tm_borders. With no other arguments this will just add a layer of drawing the borders of each polygon in the Europe object. Things get a little more interesting when we add another layer with a mapping.

4. Building a plot in layers

Let's add a tm_fill layer, mapping the fill color to the part variable, a column in the data associated with the Europe SpatialPolygonsDataFrame. Unlike ggplot2, the variable name is surrounded by quotes. There are a number of layers available in addition to borders and fill, including bubbles, dots, lines, raster and text.

5. Building a plot in layers

We can also add non data layers, like a compass with tm_compass and, similar to ggplot2 themes, control the appearance of all the other non-data elements with a tmap_style call. Although similar to ggplot2, there are some key differences to be aware of.

6. Key differences to ggplot2

tmap provides no functions equivalent to the scale_ functions in ggplot2. Any tweaks to the scale occur in the corresponding layer call instead. tm_shape defines the spatial data for any subsequent layer, and unlike a ggplot call, can be called multiple times in a plot, allowing you to layer data from different spatial objects. There is no explicit specification of x and y position aesthetics in tmap since these are inherent in spatial objects. And finally, ggplot2 uses special evaluation to avoid having to surround column names with quotes when mapping aesthetics to variables, tmap doesn't do this, so you always need to quote variable names.

7. Let's practice!