我需要标记几个重叠的多边形,但只显示最大的多边形标签。但是,当我使用一些模拟数据进行测试时,标签显示正确。我仔细比较了两种情况下的数据,但找不到造成问题的区别。
以下是模拟重叠多边形的最小示例:
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)
)
它正常工作:
然而,它并没有处理我的数据。
https://github.com/rstudio/leaflet/files/1430888/Gabs.zip
您可以将拉链拖到this site并使用i按钮查看其标记正确
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)
仅显示最大的多边形标签:
两种情况下的数据都是SpatialPolygonsDataFrame,数据槽有正确的多边形名称。
答案 0 :(得分:1)
更改hr_shape_gabs
中多边形的顺序:位置3中的多边形应该是较小的多边形。
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)
答案 1 :(得分:0)
这是sf
中基于this answer的许多层的可扩展解决方案。
该想法是通过减小尺寸来对多边形进行排序,以使最小的多边形绘制在最后。
library(sf)
library(dplyr)
# calculate area of spatial polygons sf object
poly_df$area <- st_area(poly_df)
poly_df <- arrange(poly_df, -area)
# view with labels in leaflet to see that small polygons plot on top
leaflet(poly_df) %>% addTiles() %>% addPolygons(label = ~id)
抱歉,缺乏可重复性。这更多是一个概念答案。