Home » Leaflet in R

Leaflet in R

Hello, everyone!! Today I want to show you how to display your data on a map, to do that, we need these libraries: leaflet, googleway and magrittr.

library(magrittr)
library(leaflet)
library(googleway)

For this example we will use a dataset with data to Switzerland that we can found in the Rstudio Examples, this dataset contain:Swiss Fertility and Socioeconomic Indicators(1888)

data <- datasets::swiss
head(data, 5)
##              Fertility Agriculture Examination Education Catholic
## Courtelary        80.2        17.0          15        12     9.96
## Delemont          83.1        45.1           6         9    84.84
## Franches-Mnt      92.5        39.7           5         5    93.40
## Moutier           85.8        36.5          12         7    33.77
## Neuveville        76.9        43.5          17        15     5.16
##              Infant.Mortality
## Courtelary               22.2
## Delemont                 22.2
## Franches-Mnt             20.2
## Moutier                  20.3
## Neuveville               20.6

If we want to work with leaflet, besides the name of the city we need to know the latitude and longitude of this one. In googleway we can find a function that helps us to do that. For use this library you will need a API KEY which you can get in this link, one time that you have your Api key we can continue.

Before visualizing the data we must to prepare them, for this we will add a new column with the city names.. Against more information we can give to Google, it can find more easily the correct lat and long, for this reason we add the country name with paste0()

data$City <- row.names(data)

#Now we use a loop to get the lat and long using The Googlemaps Api.
for (i in 1:nrow(data)) {
  geocode <- google_geocode(address = paste0(data$City[i],", Switzerland"), key = key)
  geocode <- as.data.frame(geocode[[1]])
  geometry <- geocode$geometry
  location <- geometry$location
  data$Long[i] <- location$lng
  data$Lat[i] <- location$lat
  
}

head(data, 5)
##              Fertility Agriculture Examination Education Catholic
## Courtelary        80.2        17.0          15        12     9.96
## Delemont          83.1        45.1           6         9    84.84
## Franches-Mnt      92.5        39.7           5         5    93.40
## Moutier           85.8        36.5          12         7    33.77
## Neuveville        76.9        43.5          17        15     5.16
##              Infant.Mortality         City     Long      Lat
## Courtelary               22.2   Courtelary 7.076310 47.17189
## Delemont                 22.2     Delemont 7.345156 47.36584
## Franches-Mnt             20.2 Franches-Mnt 7.002842 47.25487
## Moutier                  20.3      Moutier 7.371666 47.27827
## Neuveville               20.6   Neuveville 7.091263 47.06320

Now, we have the data so we can start to display the data, to do this we can use diferents visual tools like markers, circle or Popups.

Basemaps

The first step to create a map is to choose the base maps that we will need, we have 3 kinds of base maps:

Terrain:

leaflet(data, width = "100%", height = "250px") %>% addTiles()%>%
  addProviderTiles(providers$Stamen.Terrain)

Esri.WorldImagery:

leaflet(data, width = "100%", height = "250px") %>% addTiles()%>%
  addProviderTiles(providers$Esri.WorldImagery)

OpenStreetMap:

leaflet(data, width = "100%", height = "250px") %>% addTiles()%>%
  addProviderTiles(providers$OpenStreetMap)

You can find more option in this link

Add circles, Markers and pop-ups

if you want to display your data with one variable I recommend you use circles, for this example I want to display the variable Education.

#We create a color palet to display the data
MyColors<- colorNumeric(c("red", "green", "blue"), 1:100)

leaflet(data) %>% addTiles()%>%
    addProviderTiles(providers$OpenStreetMap.BlackAndWhite)%>%
  addCircles(lng = ~Long, lat = ~Lat, weight = 10,
             radius = ~Education*100, popup = paste0(
               
                       colnames(data[7]),": ", data$City, sep = "<br>",
                       colnames(data[4]),": ", data$Education), color = ~MyColors(Education)
  )

Markers

This is a good option if you want to display more of one variable in the map, in this example I display all the data.

MyColors <- colorNumeric(c("red", "green", "blue"), 1:100)

leaflet(data) %>% addTiles()%>%
    addProviderTiles(providers$OpenStreetMap.BlackAndWhite)%>%
  addMarkers( ~Long, ~Lat, popup = paste0(
                       colnames(data[7]),": ", data$City, sep = "<br>",
                       colnames(data[2]),": ", data$Agriculture, sep = "<br>",
                       colnames(data[3]),": ", data$Examination , sep = "<br>",
                       colnames(data[4]),": ", data$Education, sep = "<br>",
                       colnames(data[5]),": ", data$Catholic , sep = "<br>",
                       colnames(data[6]),": ", data$Infant.Mortality
                       )
                       ,
                     label = ~as.character(City)
                     ) 

Pop-ups

#Here we create the content of the Pop-up
content <- paste0("<h4 style='color:blue;'>",data$City,"</h2>",
                       colnames(data[4]),": ", data$Education)
leaflet(data) %>% addTiles() %>%
  addPopups(~Long, ~Lat, content,
    options = popupOptions(closeButton = FALSE)
  )

With these tips you will be able to create a beautiful and elegants maps for your reports or apps.

As always, if you have any questions you can write it in the comments.