Custom palette in tmap
Unlike ggplot2
, where setting a custom color scale happens in a scale_
call, colors in tmap
layers are specified in the layer in which they are mapped. For example, take a plot of the age_18_24
variable from prop_by_age
:
tm_shape(prop_by_age) +
tm_raster(col = "age_18_24")
Since color is mapped in the tm_raster()
call, the specification of the palette also occurs in this call. You simply specify a vector of colors in the palette
argument. This is a another reason it's worth learning ways to generate a vector of colors. While different packages could have very different shortcuts for specifying palettes from color packages, they will generally always have a way to pass in a vector of colors.
Let's use some palettes from the last exercise with this plot.
This exercise is part of the course
Visualizing Geospatial Data in R
Exercise instructions
- In the first plot, use the
blups
palette instead of the default. - In the second plot, use the
vir
palette instead of the default. - In the third plot, use the
rev(mag)
palette instead of the default.rev()
just reverses the order of a vector, so this uses the same colors but in the opposite order.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Generate palettes from last time
library(RColorBrewer)
blups <- brewer.pal(9, "BuPu")
library(viridisLite)
vir <- viridis(9)
mag <- magma(9)
# Use the blups palette
tm_shape(prop_by_age) +
tm_raster("age_18_24") +
tm_legend(position = c("right", "bottom"))
# Use the vir palette
tm_shape(prop_by_age) +
tm_raster("age_18_24") +
tm_legend(position = c("right", "bottom"))
# Use the mag palette but reverse the order
tm_shape(prop_by_age) +
tm_raster("age_18_24") +
tm_legend(position = c("right", "bottom"))