I used maps package in R in 2016 to make a geographical map and color the regions according to variable values, and then make a animation. For more details see https://www.linkedin.com/pulse/data-visualization-series-i-creating-map-r-beibei-kong.

Today, I want to introduce you to leaflet package in R to make interactive map. For more details see http://rstudio.github.io/leaflet/.

1. Display One Place

If you want to display one place, just need to google this place, get the latitude and longtitude, and then fill numbers into your code, run it, you will see this place at the center of your map.

library(leaflet)
leaflet() %>% 
  addTiles() %>% 
  setView(-93.65, 42.0285, zoom = 17)

1.1 Add Text

You could add text on the map.

library(leaflet)
leaflet() %>% 
  addTiles() %>% 
  setView(-93.65, 42.0285, zoom = 17) %>% 
  addPopups(-93.65, 42.0285, 'Here is the <b>Department of Statistics</b>, ISU')

1.2 Add Markers

You could add markers on the map, if you click the marker, it will pop up the text such as “Here is the Department of Statistics, ISU”.

leaflet() %>% 
  addTiles() %>% 
  setView(-93.65, 42.0285, zoom = 17) %>% 
  addMarkers(-93.65, 42.0285, popup = 'Here is the <b>Department of Statistics</b>, ISU')

1.3 Add Icon

You could also add icon on your map, if you click the icon, it will pop up the text.

leaflet() %>% 
  addTiles() %>% 
  addMarkers(
  c(-71.0382679, -122.1217866), 
  c(42.3489054, 47.6763144), 
  icon = list(iconUrl = 'http://www.rstudio.com/wp-content/uploads/2014/03/blue-125.png'),
  popup = c('RStudio @ Boston', 'RStudio @ Seattle'))

1.4 Add Circle Markers

You could also add circle markers on it, when you use addCircleMarkers function, if you zoom in or out the map, the size of circle will unchange, you can try it.

leaflet() %>% 
  addTiles() %>% 
  setView(-93.65, 42.0285, zoom = 17) %>% 
  addCircleMarkers(-93.65, 42.0285, color = '#ff0000')

1.5 Add Circles

When you use addCircles function, if you zoom in or out the map, the size of circle will change.

leaflet() %>% 
  addTiles() %>% 
  setView(-93.65, 42.0285, zoom = 17) %>% 
  addCircles(-93.65, 42.0285, weight = 1, radius = 30)

1.6 Add circles of different radius

You could add many circles with different radius and pop up texts for one time.

cities <- read.csv(textConnection("
City,Lat,Long,Pop
Boston,42.3601,-71.0589,645966
Hartford,41.7627,-72.6743,125017
New York City,40.7127,-74.0059,8406000
Philadelphia,39.9500,-75.1667,1553000
Pittsburgh,40.4397,-79.9764,305841
Providence,41.8236,-71.4222,177994
"))

leaflet(cities) %>% 
  addTiles() %>%
  addCircles(lng = ~Long, lat = ~Lat, weight = 1,
    radius = ~sqrt(Pop) * 30, popup = ~City)

1.7 Add circles of different colors

You could also change the color of circles by the value of one variable.

cities <- read.csv(textConnection("
City,Lat,Long,Pop
Boston,42.3601,-71.0589,645966
Hartford,41.7627,-72.6743,125017
New York City,40.7127,-74.0059,8406000
Philadelphia,39.9500,-75.1667,1553000
Pittsburgh,40.4397,-79.9764,305841
Providence,41.8236,-71.4222,177994
"))

qpal <- colorQuantile("YlOrRd", cities$Pop, n = 4)

leaflet(cities) %>% 
  addTiles() %>%
  addCircles(lng = ~Long, lat = ~Lat, weight = 1,
    popup = ~City, radius = 30000, 
    color = ~qpal(Pop), fillOpacity = 1) %>%
  addLegend("bottomright", pal = qpal, values = ~Pop, 
            title = "Pop", opacity = 1)

2. Display One Area

If you want to display one squared area, you need to provide the coordinates of the map bounds.

leaflet() %>% 
  addTiles() %>% 
  fitBounds(-118.5,33.8,-118.25,34.15)

2.1 Add Rectangle

You could add rectangle and add mini map on it.

leaflet() %>% 
  addTiles() %>% 
  fitBounds(-118.5, 33.8, -118.25, 34.15) %>% 
  addRectangles(-118.5, 33.8, -118.25, 34.15) %>% 
  addMiniMap()

2.2 Add Polygons

You could also add polygons on it.

leaflet() %>% 
  addTiles() %>% 
  fitBounds(-118.5, 33.8, -118.25, 34.15) %>% 
  addPolygons(c(-118.5, -118.3, -118.25), 
              c(33.8, 33.95, 34.15))

3. Choropleths

You could see the step-by-step choropleth tutorial in http://rstudio.github.io/leaflet/choropleths.html.

3.1 Data Source

Data used in below code could be download from http://leafletjs.com/examples/choropleth/us-states.js.

Note: Above file is a JScript Script file. You should save it as .geojson file, and then open it by notebook, delete some letters in the first line, such as “var statesData =”, save it again.

file = paste(getwd(), "/us-states.geojson", sep = '')
states <- geojsonio::geojson_read(file, what = "sp")
class(states)
## [1] "SpatialPolygonsDataFrame"
## attr(,"package")
## [1] "sp"
names(states)
## [1] "id"      "name"    "density"

3.2 Basic states map

leaflet(states) %>%
  setView(-96, 37.8, 4) %>%
  addTiles() %>% 
  addPolygons()

3.3 Adding some color

Let’s color the states according to their population density.

bins <- c(0, 10, 20, 50, 100, 200, 500, 1000, Inf)
pal <- colorBin("YlOrRd", domain = states$density, bins = bins)

leaflet(states) %>%
  setView(-96, 37.8, 4) %>%
  addTiles() %>% 
  addPolygons(fillColor = ~pal(density),
              weight = 2,
              opacity = 1,
              color = "white",
              dashArray = "3",
              fillOpacity = 0.7)

3.4 Adding interaction

We’ll make the polygons highlight as the mouse passes over them.

leaflet(states) %>%
  setView(-96, 37.8, 4) %>%
  addTiles() %>% 
  addPolygons(fillColor = ~pal(density),
              weight = 2,
              opacity = 1,
              color = "white",
              dashArray = "3",
              fillOpacity = 0.7, 
              highlight = highlightOptions(weight = 5,
                                           color = "#666",
                                           dashArray = "",
                                           fillOpacity = 0.7,
                                           bringToFront = TRUE))

3.5 Adding costom information

We’ll generate the labels by handcrafting some HTML, and passing it to lapply(htmltools::HTML) so that Leaflet knows to treat each label as HTML instead of as plain text.

labels <- sprintf(
  "<strong>%s</strong><br/>%g people / mi<sup>2</sup>",
  states$name, states$density
) %>% 
  lapply(htmltools::HTML)

m <- leaflet(states) %>%
  setView(-96, 37.8, 4) %>%
  addTiles() %>% 
  addPolygons(fillColor = ~pal(density),
              weight = 2,
              opacity = 1,
              color = "white",
              dashArray = "3",
              fillOpacity = 0.7, 
              highlight = highlightOptions(weight = 5,
                                           color = "#666",
                                           dashArray = "",
                                           fillOpacity = 0.7,
                                           bringToFront = TRUE), 
              label = labels,
              labelOptions = labelOptions(style = list("font-weight" = "normal", 
                                                       padding = "3px 8px"),
                                          textsize = "15px",
                                          direction = "auto"))

m

3.6 Adding Legend

m %>% 
  addLegend(pal = pal, values = ~density, opacity = 0.7, 
            title = NULL, position = "bottomright")

3.7 Complete Code

file = paste(getwd(), "/us-states.geojson", sep = '')
states <- geojsonio::geojson_read(file, what = "sp")

bins <- c(0, 10, 20, 50, 100, 200, 500, 1000, Inf)
pal <- colorBin("YlOrRd", domain = states$density, bins = bins)

labels <- sprintf(
  "<strong>%s</strong><br/>%g people / mi<sup>2</sup>",
  states$name, states$density
) %>% lapply(htmltools::HTML)

leaflet(states) %>%
  setView(-96, 37.8, 4) %>%
  addTiles() %>% 
  addPolygons(fillColor = ~pal(density),
              weight = 2,
              opacity = 1,
              color = "white",
              dashArray = "3",
              fillOpacity = 0.7,
              highlight = highlightOptions(weight = 5,
                                           color = "#666",
                                           dashArray = "",
                                           fillOpacity = 0.7,
                                           bringToFront = TRUE),
              label = labels,
              labelOptions = labelOptions(style = list("font-weight" = "normal", padding = "3px 8px"),
                                          textsize = "15px",
                                          direction = "auto")) %>%
  addLegend(pal = pal, values = ~density, opacity = 0.7, 
            title = NULL, position = "bottomright")

Hope this article could help you!