Plotting sf-type object in leaflet [r]
Asked Answered
S

1

13

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.

Sevenup answered 30/4, 2020 at 8:26 Comment(0)
G
12

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)

Gratin answered 1/5, 2020 at 13:15 Comment(4)
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.Demonolatry
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.Gratin
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.Demonolatry
I don't know how to do that, sorry.Gratin

© 2022 - 2024 — McMap. All rights reserved.