当 R Shiny 应用程序在网络浏览器中打开时,传单多边形失去颜色

Leaflet polygons losing colour when R Shiny app opened in web browser

我正在使用 R 中的 leaflet 构建地图,以部署为 Shiny 应用程序。 Shiny 应用程序在 RStudio 中运行良好,但是当我在网络浏览器中打开它时,多边形会失去颜色。其他一切都很好,底图在那里,多边形都在那里,您可以将鼠标悬停在多边形上以查看信息等。唯一的变化是多边形从彩色变为全灰色。没有警告或错误消息。

我正在使用最新版本的 R (3.3.3) 和 Rstudio (1.0.136) 开发 mac (Sierra),并且我的所有软件包都是最新的。我尝试了两种浏览器,结果相同(Chrome、Firefox)。特别奇怪的是,我尝试在 Windows machine 上打开应用程序,但遇到了相反的情况:Rstudio 中没有颜色,但网络浏览器 (Firefox) 中有全色。

我猜问题特别在于未能读取 addPolygons() 中的 fillColor 选项,但我不知道为什么这个选项特别有问题,以及为什么它有时有效但其他无效。如果有人有任何想法,我很想听听!

PS,我认为我的问题与 this (unanswered) question 类似,但再次令人费解的是,在我的情况下,它在 Rstudio 中有效,但在网络浏览器中无效(或在 [=25= 上相反) ] mac显然是海因斯!)。

下面是一些代码(与我正在使用的数据集不同,为清楚起见进行了修剪,但产生的行为与上述完全相同):

library(leaflet)
library(rgdal)
library(shiny)

server <- function(input,output){

  output$map <- renderLeaflet({

    # Example data (borrowed from a tutorial at https://rpubs.com/walkerke/leaflet_choropleth)
    tmp <- tempdir()
    url <- "http://personal.tcu.edu/kylewalker/data/mexico.zip"
    file <- basename(url)
    download.file(url, file)
    unzip(file, exdir = tmp)
    mexico <- readOGR(dsn = tmp, layer = "mexico", encoding = "UTF-8")

    leaflet(mexico) %>%
      addTiles() %>%
      addPolygons(weight = 1.2, label = ~name,
                  fillColor = topo.colors(4), fillOpacity = .5,
                  highlightOptions = highlightOptions(color = "black", weight = 2, bringToFront = TRUE, fillOpacity = .8)) %>%
      addProviderTiles("Esri.WorldPhysical")
  })
}

ui <- fluidPage(

  titlePanel("A map"),

  sidebarLayout(
    sidebarPanel("options go here"),
    mainPanel(
      leafletOutput("map", height = 600)
    )
  )
)

shinyApp(ui = ui, server = server)

谢谢!

topo.colors returns 带有 alpha 通道的颜色的十六进制表示。

您可以通过以下操作删除 alpha 通道部分:

gsub(".{2}$","",topo.colors(4))

不确定为什么 RStudio 查看器窗格可以处理 alpha 而不是 chrome 或 firefox。

您的传单电话可能是:

leaflet(mexico) %>%
      addTiles() %>%
      addPolygons(weight = 1.2, label = ~name,
                  fillColor = gsub(".{2}$","",topo.colors(4)), fillOpacity = .5,
                  highlightOptions = highlightOptions(color = "black", weight = 2, bringToFront = TRUE, fillOpacity = .8)) %>%
      addProviderTiles("Esri.WorldPhysical")