10

I would like to ask how to plot sf object in leaflet from leaflet package I am aware about mapview package that can plot it however I prefer using lealfet package.

I provided example down below:

library(leaflet)
library(eurostat)
library(dplyr)
library(ggplot2)

options(readr.default_locale=readr::locale(tz="Europe/Berlin"))
df60 <- get_eurostat_geospatial(resolution = 60)

CE.sf <- df60 %>%   
  dplyr::filter(LEVL_CODE == 2 & CNTR_CODE %in% c("AT","CZ","DE","HU","PL","SK")) %>% 
  dplyr::select(NUTS_ID) 

plot(CE.sf)

CE.sf %>% 
  ggplot() +
  geom_sf(color = "black", size = 0.4)

CE = sf::as_Spatial(CE.sf)

leaflet() %>% 
  addProviderTiles("CartoDB.Positron") %>% 
  addPolygons(data= CE, color = "green")

I need to reproduce plot from line 15 in leaflet, I found some ideas here: https://gis.stackexchange.com/questions/239118/r-convert-sf-object-back-to-spatialpolygonsdataframe

However using this approach does not work.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Petr
  • 1,606
  • 2
  • 14
  • 39

1 Answers1

11

You simply forgot to set the data argument in the leaflet() function. Moreover, you don't need to convert the sf object to sp format:

# packages
library(leaflet)
library(eurostat)
library(dplyr)
library(ggplot2)

options(readr.default_locale=readr::locale(tz="Europe/Berlin"))
df60 <- get_eurostat_geospatial(resolution = 60)
#> sf at resolution 1:60 read from local file

CE.sf <- df60 %>%   
  filter(LEVL_CODE == 2 & CNTR_CODE %in% c("AT","CZ","DE","HU","PL","SK")) %>% 
  select(NUTS_ID) 

plot(CE.sf)

leaflet(CE.sf) %>% 
  addProviderTiles("CartoDB.Positron") %>% 
  addPolygons(color = "green")

Created on 2020-05-01 by the reprex package (v0.3.0)

agila
  • 3,289
  • 2
  • 9
  • 20
  • Is there a way to do this without provider tiles? I don't want to see all the other parts of the map outside of the data I have. – jzadra Nov 15 '21 at 23:03
  • I think you just need to remove the CRS from the `sf` object before running `leaflet` functions. For example, run: `CE.sf = st_set_crs(CE.sf, NA)` and then the same code as before. – agila Nov 16 '21 at 10:17
  • So that produced the same thing, however I think I misstated what I was hoping to do. I would like to retain only the provider tiles that are under the polygons. – jzadra Nov 16 '21 at 19:29
  • I don't know how to do that, sorry. – agila Nov 16 '21 at 20:56