【问题标题】:Fill colours and labels not mapping correctly in Leaflet填充颜​​色和标签未在 Leaflet 中正确映射
【发布时间】:2019-08-17 08:49:18
【问题描述】:

我正在使用传单(第一次)创建一些研究成果的交互式版本。我遇到了填充颜色和标签未正确映射到 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")

【问题讨论】:

    标签: r leaflet polygon spatial sp


    【解决方案1】:

    标签不正确:
    我认为您的rownames(att) &lt;- data$station %&gt;% unique 行不正确(如果您查看att,您会发现行名与station 值不同)。
    在我看来,它应该是:rownames(att) &lt;- att$station。

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

    • 删除未使用的关卡,并使用 domain 参数构建调色板(就像您所做的那样):
      spDF$adminRegion <- fct_drop(spDF$adminRegion) factorPal <- colorFactor(viridis::viridis(n), domain = spDF$adminRegion)

    • 使用levels 参数构建调色板,只保留使用的级别:
      factorPal &lt;- colorFactor(viridis::viridis(n), levels = unique(spDF$adminRegion))

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

    【讨论】:

    • 这很简单!感谢您筛选它,因为我对传单不够熟悉,所以我不会发现其中任何一个问题
    猜你喜欢
    • 2022-12-09
    • 2012-04-14
    • 1970-01-01
    • 1970-01-01
    • 2012-04-02
    • 1970-01-01
    • 1970-01-01
    • 2021-02-22
    • 2017-07-17
    相关资源
    最近更新 更多