Get startedGet started for free

A qualitative example

Finally, let's look at an example of a categorical variable. The land_cover raster contains a gridded categorization of the earth's surface. Have a look at land_cover by printing it:

land_cover

You will notice that the values are numeric, but there are attributes that map these numbers to categories (just like the way factors work).

Choosing colors for categorical variables depends a lot on the purpose of the graphic. When you want the categories to have roughly equal visual weight -- that is, you don't want one category to stand out more than the others -- one approach is to use colors of varying hues, but equal chroma (a measure of vibrancy) and lightness (this is default for discrete color scales in ggplot2 and can be generated using the hcl() function).

The RColorBrewer qualitative palettes balance having equal visual weight colors with ease of color identification. The "paired" and "accent" schemes deviate from this by providing pairs of colors of different lightness and a palette with some more intense colors that may be used to highlight certain categories, respectively.

For this particular data, it might make more sense to choose intuitive colors, like green for forest and blue for water. Whichever is more appropriate, setting new colors is just a matter of passing in a vector of colors through the palette argument in the corresponding tm_*** layer.

This exercise is part of the course

Visualizing Geospatial Data in R

View Course

Exercise instructions

  • Plot the land_cover raster by combining tm_shape() and tm_raster(). By default tmap uses the RColorBrewer "Set3" qualitative palette.
  • Examine the code for hcl_cols, which mimics the palette used by ggplot2. Then plot the land_cover raster again, passing hcl_cols to the palette argument to tm_raster().
  • Call levels() on land_cover to see the categories.
  • This time, use intuitive_cols as the palette and add a tm_legend() layer with the argument position = c("left", "bottom").

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

library(raster)

# Plot land_cover



# Palette like the ggplot2 default
hcl_cols <- hcl(h = seq(15, 375, length = 9), 
                c = 100, l = 65)[-9]

# Use hcl_cols as the palette



# Examine levels of land_cover


# A set of intuitive colors
intuitive_cols <- c(
  "darkgreen",
  "darkolivegreen4",
  "goldenrod2",
  "seagreen",
  "wheat",
  "slategrey",
  "white",
  "lightskyblue1"
)

# Use intuitive_cols as palette


Edit and Run Code