Exercise

Building a plot in layers

Now that you know a bit more about tmap(), let's build up your previous plot of population in layers and make a few tweaks to improve it. You start with a tm_shape() layer that defines the data you want to use, then add a tm_fill() layer to color-in your polygons using the variable population:

tm_shape(countries_spdf) +
  tm_fill(col = "population") 

Probably the biggest problem with the resulting plot is that the color scale isn't very informative: the first color (palest yellow) covers all countries with population less than 200 million! Since the color scale is associated with the tm_fill() layer, tweaks to this scale happen in this call. You'll learn a lot more about color in Chapter 3, but for now, know that the style argument controls how the breaks are chosen.

Your plot also needs some country outlines. You can add a tm_borders() layer for this, but let's not make them too visually strong. Perhaps a brown would be nice.

The benefit of using spatial objects becomes really clear when you switch the kind of plot you make. Let's also try a bubble plot where the size of the bubbles correspond to population. If you were using ggplot2, this would involve a lot of reshaping of your data. With tmap, you just switch out a layer.

Instructions

100 XP
  • Add style = "quantile" to tm_fill(). This chooses the breaks in the color scale based on equal numbers of observations in each interval.
  • To the same plot, add a tm_borders() layer with col = "burlywood4".
  • Create new plot the same as the first, but instead of tm_fill() add a tm_bubbles() layer with size mapped to population.