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
Exercise instructions
- Plot the
land_cover
raster by combiningtm_shape()
andtm_raster()
. By defaulttmap
uses theRColorBrewer
"Set3"
qualitative palette. - Examine the code for
hcl_cols
, which mimics the palette used byggplot2
. Then plot theland_cover
raster again, passinghcl_cols
to thepalette
argument totm_raster()
. - Call
levels()
onland_cover
to see the categories. - This time, use
intuitive_cols
as the palette and add atm_legend()
layer with the argumentposition = 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