R que R

Leaflet maps (Part III)

Wed, Apr 8, 2020
R
#leaflet #raster #mapas #maps #choropleth



# PACKAGES / LIBRARIES:


library(tidyverse)
library(leaflet)
library(readxl)
library(leaflet.providers)
library(raster)
library(sf)


Intro


Leaflet is an open source JavaScript library used to build web mapping applications. It creates embedding maps with tiled base layers, interactive panning and zooming and feature layers.


The {leaflet} R package allows to integrate and control Leaflet maps in R and to create maps from the R console or from RStudio. {leaflet} also provides interactive panning and zooming and allows rendering spatial objects from the {sp} or {sf} packages or from dataframes with latitude and longitude coordinates. There is also a leaflet plugins repository that you can use to add more features/plugins to your maps.


This third post will present a choropleth map that will indicate the average income per inhabitant at a Municipality level in Spain in 2016 (but the map will only show those municipalities with average income higher than 12000 euros).


Spain: Average Income by Municipality (2016)



renta_media <- read_excel("C:/Users/Usuario/Desktop/r_que_r/r_que_r/content/datasets/renta_media.xls")

renta_media$renta_media <- as.numeric(renta_media$renta_media)

renta_media<- renta_media %>%
  separate(Municipio, c("cod", "municipio"), 
           sep = " ", 
           extra = "merge") 


# Shapefiles municipios Spain
spain_shapefiles <- read_sf("C:/Users/Usuario/Desktop/r_que_r/r_que_r/content/datasets/Municipios_IGN")


renta_Spain_map <- spain_shapefiles %>%
  dplyr::left_join(renta_media, by=c("CODIGOINE" = "cod")) %>%
  dplyr::select(OBJECTID, Provincia, municipio, renta_media) %>%
  dplyr::filter(renta_media > 12000)


mybins<-c(12000, 15000, 18000, 21000, 24000, 27000)

my_pal <- colorBin(
  palette = "Spectral", 
  domain = renta_Spain_map$renta_media,
  na.color = "transparent",
  bins = mybins)

renta_Spain_map %>%
  leaflet() %>%
  addProviderTiles(providers$Esri.WorldShadedRelief) %>%
  addPolygons(
    weight = 0.6,
    stroke = TRUE,
    color = "white",
    fillColor = ~my_pal(renta_media),
    fillOpacity = 1,
    dashArray = "3",
    label = ~municipio,
    popup = ~paste("Municipality:", municipio,
                   "<br/>",
                   "Province:", Provincia,
                   "<br/>",
                   "Avg. Income:", renta_media),
    highlight = highlightOptions(
      weight = 2,
      dashArray = "",
      color = "grey",
      bringToFront = TRUE
  )) %>%
  addLegend( pal= my_pal, 
             values = ~renta_media, 
             opacity = 0.9, 
             title = "Average Income per inhabitant (2016)", 
             position = "bottomright")



Click here to see the map.