【问题标题】:r - Shiny+leaflet: How to set Markers color depend on user inputr - Shiny+leaflet:如何设置标记颜色取决于用户输入
【发布时间】:2018-07-21 18:27:29
【问题描述】:

我使用闪亮和传单在地图上添加了点。 每个点都是不同类型的交通选择。 我想按颜色区分不同的类型,但无法弄清楚。 尝试使用不起作用的“if”。 谢谢!

这是我的基本代码

library(leaflet)
ui <- fluidPage(
leafletOutput("map"),
headerPanel("Example"),
sidebarPanel(checkboxGroupInput(inputId = "Type", label = "Data 
Layer",choices = c("Bike", "Muni", "Bus", "BART"), selected = "Bike")))

server <- function(input, output) {
output$map <- renderLeaflet({

rownumber = which(Stops_and_stations$Type == input$Type)
x <- Stops_and_stations[rownumber,]

leaflet(width = 1000, height = 500) %>% 
  addTiles() %>% 
  addCircleMarkers(lng = x$stop_lon,
                   lat = x$stop_lat,
                   radius= 3, color = '#ff6633') %>% 
  setView(lng = -122.4000,
          lat = 37.79500,
          zoom = 13)
})
}
shinyApp(ui, server)

这就是我试图添加的 .....

 if(input$Type == "Bike"){

leaflet(width = 1000, height = 500) %>% 
  addTiles() %>% 
  addCircleMarkers(lng = x$stop_lon,
                   lat = x$stop_lat,
                   radius= 3, color = '#ff6633') %>% 
  setView(lng = -122.4000,
          lat = 37.79500,
          zoom = 13)
}

if(input$Type == "Muni"){

leaflet(width = 1000, height = 500) %>% 
  addTiles() %>% 
  addCircleMarkers(lng = x$stop_lon,
                   lat = x$stop_lat,
                   radius= 3, color = '#0033ff') %>% 
  setView(lng = -122.4000,
          lat = 37.79500,
          zoom = 13)
}

.....

【问题讨论】:

  • 我们无权访问 Stops_and_stations$Type

标签: r shiny leaflet r-leaflet


【解决方案1】:

如果您提供Stops_and_stations 并因此将其设为reproducible example..

,那么回答您的问题会容易得多

为不同组使用不同颜色的一种方法是将color 列添加到您的data.frame

由于我们不知道您的数据,我创建了一些随机数据集。

Stops_and_stations <- data.frame(
  Type = rep(c("Bike", "Muni", "Bus", "BART"), each = 10),
  stop_lon = -runif(40, 122.4200, 122.4500),
  stop_lat = runif(40, 37.76800, 37.78900),
  color = rep(c("Red", "Blue", "Green", "Yellow"), each = 10)
)

然后,您可以使用color 列,而不是指定具体的颜色,例如#ff6633

addCircleMarkers(lng = x$stop_lon,
                       lat = x$stop_lat,
                       radius= 3, color = x$color)

我还要指出您的子集不正确:您使用的是checkboxGroupInput,它可以有更多的值,因此您需要使用%in% 运算符进行过滤。

x <- Stops_and_stations[Stops_and_stations$Type %in% input$Type,]

【讨论】:

    猜你喜欢
    • 2019-05-02
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    • 2018-02-26
    • 2021-10-24
    • 2022-07-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多