Skip to content
Mapping with R has been completely revamped. Check it out →
R for the Rest of Us Logo

Mapping with R

Making Choropleth Maps with {leaflet}

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(leaflet)
library(tidyverse)
library(tidycensus)
library(janitor)
library(tigris)
library(scales)
library(sf)

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

speak_language_other_than_english_wgs84_with_labels

my_palette <-
  colorNumeric(
    palette = "viridis",
    domain = speak_language_other_than_english_wgs84_with_labels$pct
  )

leaflet() |>
  setView(-93.65, 42.0285, zoom = 2) |>
  addProviderTiles("CartoDB.Positron") |>
  addPolygons(
    data = speak_language_other_than_english_wgs84_with_labels,
    weight = 0.75,
    fillColor = ~ my_palette(pct),
    fillOpacity = 0.8,
    color = "white",
    popup = ~text_label
  ) |>
  addLegend(
    position = "topright",
    pal = my_palette,
    values = speak_language_other_than_english_wgs84_with_labels$pct,
    labFormat = labelFormat(
      transform = function(x) sort(x * 100, decreasing = TRUE),
      suffix = "%"
    ),
    opacity = 0.8
  )

Your Turn

Using the code to make your map on refugee populations from the last lesson, turn your map into a choropleth, with different shading for countries with higher refugee populations.

Learn More

To learn about using the setView() function, check out this vignette.

Choropleths in {leaflet} are covered in this vignette, and legends in this vignette.

To learn more about the viridis palette we used, check out this vignette from the {viridis} package.

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

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

Jessica Cacioppo

Jessica Cacioppo • May 12, 2025

When reversing the labels in the legend to show 80% at the top instead of the bottom, you also need to reverse the colors because now the legend is showing yellow as 0% but it is actually 80%.

David Keyes

David Keyes Founder • May 12, 2025

Good point, thanks!

Andrew Pickering

Andrew Pickering • May 12, 2025

I think there is an issue with the legend; the colors and values don't match up correctly when the legend values are reversed. The legend numbers get flipped, but the colorbar doesn't flip.

David Keyes

David Keyes Founder • May 12, 2025

Oh yeah, you're right. 😬 I'll see if I can re-record this soon!