Skip to content
R for the Rest of Us Logo

Mapping with R

Adding Text Labels to {leaflet} Maps

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 <-
  read_sf(
    "https://raw.githubusercontent.com/rfortherestofus/mapping-with-r-v2/refs/heads/main/data/speak_language_other_than_english_wgs84.geojson"
  )

speak_language_other_than_english_wgs84_with_labels <-
  speak_language_other_than_english_wgs84 |>
  mutate(
    text_label = str_glue(
      "<b>{percent(pct, accuracy = 0.1)}</b> of the population of <b>{name}</b> speaks a language other than English"
    )
  )

leaflet() |>
  addProviderTiles("CartoDB.Positron") |>
  addPolygons(
    data = speak_language_other_than_english_wgs84,
    weight = 1
  )

leaflet() |>
  addProviderTiles("CartoDB.Positron") |>
  addPolygons(
    data = speak_language_other_than_english_wgs84,
    weight = 1,
    popup = ~name
  )

leaflet() |>
  addProviderTiles("CartoDB.Positron") |>
  addPolygons(
    data = speak_language_other_than_english_wgs84_with_labels,
    weight = 1,
    popup = ~text_label
  )

Your Turn

Using the code to make your map from the last lesson on refugee populations, add a label and/or popup that shows the number of refugees from each country.

Learn More

The popups and labels vignette shows how to use them within {leaflet}.

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

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