Static Maps in R

HES 505 Fall 2022: Session 25

Matt Williamson

Objectives

By the end of today you should be able to:

  • Construct a map using ggplot2 and tmap

  • Combine vector and raster data in the same map

  • Add annotations and inset maps to decorate your map

Building Choropleth Maps

Using ggplot2

cty.info <- get_acs(geography = "county", 
                      variables = c(pop="B01003_001", 
                                    medincome = "B19013_001"),
                      survey="acs5",
                      state = c("WA", "OR", "ID", "MT", "WY"),
                      geometry = TRUE, key = censkey, progress_bar=FALSE) %>% 
  select(., -moe) %>% 
  pivot_wider(
    names_from = "variable",
    values_from = "estimate"
  )

p <- ggplot(data=cty.info) +
  geom_sf(mapping=aes(fill=medincome))

Static Maps with ggplot2

Changing aesthetics

p <- ggplot(data=cty.info) +
  geom_sf(mapping=aes(fill=pop), color="white") +
  scale_fill_viridis()

Changing aesthetics

Adding layers

st <- tigris::states(progress_bar=FALSE) %>% 
  filter(., STUSPS %in% c("WA", "OR", "ID", "MT", "WY"))

p <- ggplot(data=cty.info) +
  geom_sf(mapping=aes(fill=pop), color="white") +
  geom_sf(data=st, fill=NA, color="red") +
  scale_fill_viridis()

Adding layers

Creating a custom theme

theme_map <- function(...) {
  theme_minimal() +
    theme(
      #text = element_text(family = "Ubuntu Regular", color = "#22211d"),
      axis.line = element_blank(),
      axis.text.x = element_blank(),
      axis.text.y = element_blank(),
      axis.ticks = element_blank(),
      axis.title.x = element_blank(),
      axis.title.y = element_blank(),
      #panel.grid.minor = element_line(color = "#ebebe5", size = 0.2),
      panel.grid.major = element_line(color = "white", 
                                      size = 0.002),
      panel.grid.minor = element_line(color = "white", 
                                      size = 0.002),
      plot.background = element_rect(fill = "white", 
                                     color = NA), 
      panel.background = element_rect(fill = "white", 
                                      color = NA), 
      legend.background = element_rect(fill = "white", 
                                       color = NA),
      panel.border = element_blank(),
      ...
    )
}

Using tmap

pt <- tm_shape(cty.info) + 
  tm_polygons(col = "pop",
              border.col = "white") + 
  tm_legend(outside = TRUE)

Using tmap

Changing aesthetics

pt <- tm_shape(cty.info) + 
  tm_polygons(col = "pop", n=10,palette=viridis(10),
              border.col = "white") + 
  tm_legend(outside = TRUE)

Changing aesthetics

Adding layers

Integrating Rasters

Ornamentation