填充Leaflet中未正确映射的颜色和标签

问题描述 投票:0回答:1

我正在使用传单(第一次)创建一些研究输出的交互式版本。我有一个问题,填充颜色和标签没有正确映射到shapefile。

我确定这个错误归咎于我某个地方,但经过两个晚上我无法理解。下面是使用简化数据集的示例。我上传了数据https://gofile.io/?c=DKvFwr

pacman::p_load(tidyverse, data.table, leaflet, sp, maps, leaflet.extras, htmltools, rgdal)


# Load data
data = readRDS("exampleData.RDS")
data %>% str


# Create spatial polygons dataframe
spPolys = data %>%
  group_by(station) %>%
  do(poly=select(., long, lat) %>% Polygon()) %>%
  rowwise() %>%
  do(polys=Polygons(list(.$poly),.$station)) %>%
  {SpatialPolygons(.$polys)}

att = data %>% group_by(station) %>% slice(1) %>% select(station, adminRegion, nestedLevel, river, location, area_km2, type) %>% as.data.frame
rownames(att) <- data$station %>% unique

spDF = SpatialPolygonsDataFrame(spPolys, data = att)
spDF@data


# Mapping
n = length(unique(spDF$adminRegion))
factorPal <- colorFactor(viridis::viridis(n), spDF$adminRegion)

spDF %>%
  leaflet() %>%

  addProviderTiles(provider = providers$Esri.WorldGrayCanvas) %>%

  addPolygons(stroke = FALSE, smoothFactor = 0.2, 
              fillOpacity = 1.0, fillColor = ~factorPal(adminRegion), 
              label = ~adminRegion) %>%

  addLegend(pal = factorPal, values = ~adminRegion, 
            opacity = 1.0, title = NULL,
            position = "bottomright")

enter image description here

r leaflet polygon spatial sp
1个回答
0
投票

标签不正确: 我认为你的行rownames(att) <- data$station %>% unique是不正确的(如果你看看att,你可以看到rownames与station值不同)。 在我看来,它应该是:rownames(att) <- att$station

颜色: 当使用colorFactor()时,它会考虑变量的所有级别。如果你看看spDF$adminRegion的水平,你可以看到所有原始的14级data$adminRegion仍然存在。 你有两个解决方案:

  • 删除未使用的级别,并使用domain参数构建调色板(如您所做): spDF$adminRegion <- fct_drop(spDF$adminRegion) factorPal <- colorFactor(viridis::viridis(n), domain = spDF$adminRegion)
  • 使用levels参数构建调色板,仅保留使用的级别: factorPal <- colorFactor(viridis::viridis(n), levels = unique(spDF$adminRegion))

第一种解决方案为您提供与ggplot2完全相同的颜色。

© www.soinside.com 2019 - 2024. All rights reserved.