leaflet icon indicating copy to clipboard operation
leaflet copied to clipboard

R leaflet incorrect polygon label after st_intersection

Open Armandjg opened this issue 2 years ago • 0 comments

I have zip code data for the US and plotting it yields the correct labels, however, once I use st_intersection with these polygons, the labels become mismatched.

The label mismatch happens when using leaflet but not when using the mapview library.

library(sf)
library(tidyverse)
library(leaflet)
library(sp)

sf_use_s2(FALSE)
crs4326 <- CRS("+init=epsg:4326")

# MUAs ------------------------------------------------------------------
dir.create("MUA_Folder")
download.file("https://data.hrsa.gov//DataDownload/DD_Files/MUA_SHP.zip",destfile = "MUAs.zip")

unzip(overwrite = T,
      zipfile = "MUAs.zip",
      unzip = "unzip",exdir = "./MUA_Folder")

MUAs <- read_sf("MUA_Folder/MUA_SHP_DET_CUR_VX.shp")
MUA_NY <- MUAs[MUAs$CStAbbr=="NY",]


# States ------------------------------------------------------------------
dir.create("States")
download.file("https://www2.census.gov/geo/tiger/GENZ2018/shp/cb_2018_us_state_500k.zip",destfile = "States.zip")

unzip(overwrite = T,
      zipfile = "States.zip",
      unzip = "unzip",exdir = "./States")

States <- read_sf("Data/States/cb_2018_us_state_500k.dbf") %>% st_transform(crs = crs4326)
st_geometry(States) <- "State_geometry"
States$NAME2 <- gsub(" ","",States$NAME)


# Zip Codes ------------------------------------------------------------------
download.file("https://www2.census.gov/geo/tiger/TIGER2022/ZCTA520/tl_2022_us_zcta520.zip",destfile = "ZipCodes.zip")
dir.create("ZipCodes")

unzip(overwrite = T,
      zipfile = "ZipCodes.zip",
      unzip = "unzip",exdir = "./ZipCodes")

read_sf("ZipCodes/cb_2018_us_zcta510_500k.dbf")

ZC <- read_sf("Data/ZCTAs/tl_2022_us_zcta520.dbf") %>% st_transform(crs = crs4326) #Zip Codes
#ZCNY <- ZC[ZC$State=="NY",]

ZCNY<- st_intersection(ZC,States[States$NAME == 'New York',])

#Zip Code NY 
NYPoly <- st_intersection(ZCNY[!st_is_empty(ZCNY),],
                         MUA_NY[!st_is_empty(MUA_NY),],
                by.feature = T)

Poly[st_is_empty(Poly),] # No rows returned
MUA_NY[st_is_empty(MUA_NY),] # No rows returned

#Labels used:
maplabsNY <-  as.list( paste("Zip: ", NYPoly$ZCTA5CE20, "<br>",
                           "City: ", NYPoly$City, "<br>",
                           "Population: ", NYPoly$EstimatedPopulation2, "<br>"))

leaflet() %>%
  addProviderTiles(providers$CartoDB.Positron) %>%
  addPolygons(
    # data = st_collection_extract(ZCNY,type = "POLYGON"), #Correct Labels, but too many zips
    data = st_collection_extract(NYPoly,type = "POLYGON"), #Incorrect Labels, correct number of zips
    group = "Zipcodes",
   #fillColor =  ~pal(MAPVALS),
    weight = 1,
    stroke = 1,
    smoothFactor = .2,
    opacity = .4,
    fillOpacity = .9,
    label = lapply(maplabsNY, HTML),
    highlightOptions = highlightOptions(
      color = "white",
      weight = 3,
      bringToFront = F
    ) 
  ) 

Correct labels:

Correct Label

Incorrect labels: Incorrect Label

When I remove and then reattach the geometries, I get a different set of polygons (the full zip code geometry instead of the intersected segment) with the correct labels:

PolyNY$geometry <- NULL
PolyNY<- left_join(PolyNY,ZCNY) 

Correct labels, but with extra (unwanted) polygons: image

R version 4.2.2 (2022-10-31 ucrt) Platform: x86_64-w64-mingw32/x64 (64-bit) Running under: Windows 10 x64 (build 19045)

Matrix products: default

> sf_extSoftVersion()
          GEOS           GDAL         proj.4 GDAL_with_GEOS     USE_PROJ_H           PROJ 
       "3.9.3"        "3.5.2"        "8.2.1"         "true"         "true"        "8.2.1" 

locale:
[1] LC_COLLATE=English_Canada.utf8  LC_CTYPE=English_Canada.utf8    LC_MONETARY=English_Canada.utf8 LC_NUMERIC=C                   
[5] LC_TIME=English_Canada.utf8    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

loaded via a namespace (and not attached):
[1] compiler_4.2.2  cli_3.4.1       tools_4.2.2     rstudioapi_0.14

Leaflet version: 2.1.1

Expected behavior

Leaflet map labels will show the correct information with each polygon after using st_intersection.

Current behavior

Leaflet map labels show incorrect/reordered information with each polygon after using st_intersection.

Armandjg avatar Jan 03 '23 18:01 Armandjg