Skip to content
R for the Rest of Us Logo

Mapping with R

Combining Multiple Geometries

Transcript

Click on the transcript to go to that point in the video. Please note that transcripts are auto generated and may contain minor inaccuracies.

View code shown in video
library(sf)
library(tidyverse)
library(scales)

city_council_districts <-
  read_sf("https://raw.githubusercontent.com/rfortherestofus/mapping-with-r-v2/refs/heads/main/data/portland_city_council_districts.geojson")

city_council_districts |>
  mapview::mapview()

improved_corners_by_district <-
  read_sf("https://raw.githubusercontent.com/rfortherestofus/mapping-with-r-v2/refs/heads/main/data/improved_corners_by_district.geojson")

improved_corners_by_area <-
  improved_corners_by_district |>
  mutate(
    area = case_when(
      district == "District 4" ~ "Westside",
      .default = "Eastside"
    )
  ) |>
  group_by(area, ramp_style) |>
  summarize(n = sum(n)) |>
  ungroup() |>
  group_by(area) |>
  mutate(pct = n / sum(n)) |>
  ungroup()

improved_corners_by_area |>
  filter(ramp_style == "Improved") |>
  ggplot() +
  geom_sf(aes(fill = pct)) +
  labs(fill = NULL) +
  scale_fill_viridis_c(
    option = "B",
    limits = c(0.25, 0.35),
    labels = percent_format(accuracy = 1)
  ) +
  theme_void() +
  theme(
    legend.position = "top",
    legend.key.width = unit(2, "cm"),
    legend.key.height = unit(0.5, "cm")
  )

Your Turn

Combine all of the sextants to make a map that shows the Portland boundaries.

Learn More

In this lesson, I only covered using group_by() and summarize() to combine geometries and values within them. If you just need to combine geometries, you can also use the st_union() function.

Have any questions? Put them below and we will help you out!

You need to be signed-in to comment on this post. Login.