LoslegenKostenlos loslegen

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.

Diese Übung ist Teil des Kurses

Visualizing Geospatial Data in R

Kurs anzeigen

Anleitung zur Übung

  • 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.

Interaktive Übung

Versuche dich an dieser Übung, indem du diesen Beispielcode vervollständigst.

# 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"))
Code bearbeiten und ausführen