【问题标题】:Leaflet rendering incorrect countries传单渲染不正确的国家
【发布时间】:2018-09-22 16:53:38
【问题描述】:

我正在尝试使用 leaflet 绘制几个国家/地区,但它显示的国家/地区不正确。以下是我的最小可重现示例:

library(leaflet)
library(maps)


  df <- data.frame(name = c("Afghanistan", "Albania" , "Algeria" , "Armenia"),
                   code = c("AFG", "ALB", "DZA", "ARM"),
                    val = c(5, 10, 15, 20), stringsAsFactors = FALSE)

  pal <- colorNumeric(
    palette = "Blues",
    domain = as.numeric(df$val))

  labels <- sprintf(
    "<strong>Country:%s</strong><br/>Value:%g /",
    df$name, df$val)%>% lapply(htmltools::HTML) 

  Country = map("world", fill = TRUE, plot = FALSE, regions=iso.expand(df$code,regex = TRUE))

  leaflet(Country) %>% addTiles() %>%
    addPolygons(fillOpacity = 0.6,  smoothFactor = 0.5, stroke = TRUE, weight = 1, 
                color = ~pal(as.numeric(df$val)),
                label = labels)

我收到以下传单:

如您所见,阿尔及利亚显示为阿尔巴尼亚。如果我从我的数据中删除亚美尼亚并绘制传单,我会得到正确的位置。以下是它的代码和图像。

library(leaflet)
  library(maps)

  df <- data.frame(name = c("Afghanistan", "Albania" , "Algeria" ),
                   code = c("AFG", "ALB", "DZA"),
                    val = c(5, 10, 15), stringsAsFactors = FALSE)

  pal <- colorNumeric(
    palette = "Blues",
    domain = as.numeric(df$val))

  labels <- sprintf(
    "<strong>Country:%s</strong><br/>Value:%g /",
    df$name, df$val)%>% lapply(htmltools::HTML) 

  Country = map("world", fill = TRUE, plot = FALSE, regions=iso.expand(df$code,regex = TRUE))

  leaflet(Country) %>% addTiles() %>%
    addPolygons(fillOpacity = 0.6,  smoothFactor = 0.5, stroke = TRUE, weight = 1, 
                color = ~pal(as.numeric(df$val)),
                label = labels)

我错过了什么吗?

【问题讨论】:

    标签: r leaflet


    【解决方案1】:

    我认为这个问题与map 对象中的多边形顺序有关(如果您设置了label = Country$names,标签现在是正确的)。无论如何,您可以通过将Country 转换为SpatialPolygons 对象来解决问题(参见here)。

    library(maptools)
    IDs <- sapply(strsplit(Country$names, ":"), function(x) x[1])
    Country <- map2SpatialPolygons(Country, 
                                   IDs=IDs, 
                                   proj4string=CRS("+proj=longlat +datum=WGS84"))
    
    leaflet(Country) %>% addTiles() %>%
      addPolygons(fillOpacity = 0.6,  smoothFactor = 0.5, stroke = TRUE, weight = 1, 
                  color = pal(as.numeric(df$val)),
                  label = labels)
    

    【讨论】:

    • 正是我需要的!
    • 它在这种情况下解决了问题,但在我的实际代码中,有更多国家/地区的问题仍然存在。关于如何解决这个问题的任何指示?
    • 您可以使用SpatialPolygonsDataframepal(as.numeric(df$val)labelsCountry 合并,并在addPolygons 函数中使用Country$valCountry$label。像这样,vallabels 应该与正确的国家/地区相关联。
    猜你喜欢
    • 2011-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-17
    相关资源
    最近更新 更多