0

I am starting to become familiar with leaflet in R although I am experiencing some issues. Data works properly when I am plotting the map with ggplot2. However, I was asked to switch to a more dynamic and interactive map for a shiny dashboard. Here I report the code I performed with the image of the 'grey' results I obtained. I am plotting some Italian provincial data. I retrieved the shape file from the website of the Italian Institute of Statistics (2020, versione generalizzata). Nonetheless, I have uploaded the dataframe and the shape file also on GitHub.

library(dplyr)
library(leaflet)
library(rgdal)
library(sf)

# Import data 
load('C:/[...]/data_19.rda') # <--- There are several variables, I selected just one of them

# Import Italy shapefile
ita_map = readOGR('C:/[...]/Limiti01012020_g/ProvCM01012020_g', 
                  'ProvCM01012020_g_WGS84', stringsAsFactors = FALSE)

# Merge
colnames(data_19)[1] = "COD_PROV" # <--- This is the numerical provincial code
ita_map_sf = st_as_sf(ita_map)
ita_map_data <- left_join(ita_map_sf, data_19, by = "COD_PROV")

# Generate map with leaflet
ita_map_data %>%
  st_transform(crs = 4326) %>%
  leaflet() %>%
  addProviderTiles("Esri.WorldGrayCanvas") %>%
  setView(lat = 41.8719, lng = 12.5674, zoom = 5) %>%
  addPolygons(
    fillColor = ita_map_data$unilav_ula,
    stroke = FALSE,
    smoothFactor = 0.2,
    fillOpacity = 0.3
  )

Here, instead, the result I am getting from the viewer: enter image description here

I guess there are some problems in the way I dealt with the polygon data frame. I hope someone could give me some hints. Thank you in advance.

1 Answer 1

2

See the R leaflet documentation page for plotting Choropleth Maps:

https://rstudio.github.io/leaflet/choropleths.html

You need to specify a color palette you want to use for the map. The following code produces the output below.

library(dplyr)
library(leaflet)
library(rgdal)
library(sf)

# Import data 
load('C:/[...]/data_19.rda') # <--- There are several variables, I selected just one of them

# Import Italy shapefile
ita_map = readOGR('C:/[...]/Limiti01012020_g/ProvCM01012020_g', 
                  'ProvCM01012020_g_WGS84', stringsAsFactors = FALSE)

# Merge
colnames(data_19)[1] = "COD_PROV" # <--- This is the numerical provincial code
ita_map_sf = st_as_sf(ita_map)
ita_map_sf$COD_PROV <- as.numeric(ita_map_sf$COD_PROV)
ita_map_data <- left_join(ita_map_sf, data_19, by = "COD_PROV")

# Specify Color Palette
pal <- colorQuantile("Blues", domain = ita_map_data$unilav_ula, n=5)

# Generate map with leaflet
ita_map_data %>%
  st_transform(crs = 4326) %>%
  leaflet() %>%
  addProviderTiles("Esri.WorldGrayCanvas") %>%
  setView(lat = 41.8719, lng = 12.5674, zoom = 5) %>%
  addPolygons(
    fillColor = ~pal(unilav_ula),
    stroke = FALSE,
    smoothFactor = 0.2,
    fillOpacity = 0.7,
    label=~unilav_ula
  )

Output map

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.