12.8 Map using leaflet

Next, we create an interactive map with the PM2.5 values of each country by using the leaflet package (Figure 12.4). To color the countries according to their PM2.5 values, we first create a color palette. We call this palette pal and create it by using the colorNumeric() function with argument palette equal to viridis, domain equal to the PM2.5 values, and cut points equal to the sequence from 0 to the maximum PM2.5 values in increments of 10. To create the map, we use the leaflet() function passing the map object. We write addTiles() to add a background map, and add setView() to center and zoom the map. Then we use addPolygons() to plot the areas of the map. We color the areas with the colors given by the PM2.5 values and the palette pal.

library(leaflet)

pal <- colorBin(
  palette = "viridis", domain = map$PM2.5,
  bins = seq(0, max(map$PM2.5, na.rm = TRUE) + 10, by = 10)
)


map$labels <- paste0(
  "<strong> Country: </strong> ",
  map$NAME, "<br/> ",
  "<strong> PM2.5: </strong> ",
  map$PM2.5, "<br/> "
) %>%
  lapply(htmltools::HTML)

leaflet(map) %>%
  addTiles() %>%
  setView(lng = 0, lat = 30, zoom = 2) %>%
  addPolygons(
    fillColor = ~ pal(PM2.5),
    color = "white",
    fillOpacity = 0.7,
    label = ~labels,
    highlight = highlightOptions(
      color = "black",
      bringToFront = TRUE
    )
  ) %>%
  leaflet::addLegend(
    pal = pal, values = ~PM2.5,
    opacity = 0.7, title = "PM2.5"
  )