Search code examples
rr-leaflet

Label for overlapping polygons in R leaflet


I need to label several overlapping polygons, but only the label of the biggest one is shown. However when I tested with some simulated data the labels were shown correctly. I compared the data in two cases carefully but cannot find the difference caused the problem.

Here is a minimal example of simulated overlapping polygons:

library(leaflet)
library(sp)

poly_a <- data.frame(lng = c(0, 0.5, 2, 3),
                     lat = c(0, 4, 4, 0))
poly_b <- data.frame(lng = c(1, 1.5, 1.8),
                     lat = c(2, 3, 2))
pgons = list(
  Polygons(list(Polygon(poly_a)), ID="1"),
  Polygons(list(Polygon(poly_b)), ID="2")
)
poly_dat <- data.frame(name = as.factor(c("a", "b")))
rownames(poly_dat) <- c("1", "2")

spgons = SpatialPolygons(pgons)
spgonsdf = SpatialPolygonsDataFrame(spgons, poly_dat, TRUE)

leaflet() %>% addPolygons(data = spgonsdf, label = ~name
                          #           ,
                          #           highlightOptions = highlightOptions(
                          # color = "red", weight = 2,bringToFront = TRUE)
)

It's working properly:

enter image description here

enter image description here

However it didn't work with my data.

https://github.com/rstudio/leaflet/files/1430888/Gabs.zip

You can drag the zip into this site and use the i button to see it's correctly labeled

enter image description here enter image description here

library(rgdal)

# download Gabs.zip and extract files to Gabs folder
hr_shape_gabs <- readOGR(dsn = 'Gabs', layer = 'Gabs - OU anisotropic')
hr_shape_gabs_pro <- spTransform(hr_shape_gabs, 
                                 CRS("+proj=longlat +datum=WGS84 +no_defs"))
leaflet(hr_shape_gabs_pro) %>%
  addTiles() %>% 
  addPolygons(weight = 1, label = ~name)

Only the biggest polygon label is shown:

enter image description here

enter image description here

The data in both case are SpatialPolygonsDataFrame, the data slot have proper polygon names.


Solution

  • Change the order of polygons in hr_shape_gabs: polygon in position 3 should be the smaller one.

    library(leaflet)
    library(sp)
    library(rgdal)
    hr_shape_gabs <- readOGR(dsn = 'Gabs - OU anisotropic.shp', 
                             layer = 'Gabs - OU anisotropic')
    
    # Change the position of the smaller and wider polygons
    # Position 1 = wider polygon, position 3 = smaller polygon
    pol3 <- hr_shape_gabs@polygons[[3]]
    hr_shape_gabs@polygons[[3]] <- hr_shape_gabs@polygons[[1]]
    hr_shape_gabs@polygons[[1]] <- pol3
    hr_shape_gabs$name <- rev(hr_shape_gabs$name)
    
    hr_shape_gabs_pro <- spTransform(hr_shape_gabs, 
                                     CRS("+proj=longlat +datum=WGS84 +no_defs"))
    leaflet() %>%
      addTiles() %>% 
      addPolygons(data= hr_shape_gabs_pro, weight = 1, label = ~name)
    

    enter image description here