如何根据列设置标记颜色?

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

我需要根据

if
条件使圆圈具有不同的颜色。我在
if
参数中添加了
color=
语句,但所有圆圈仅以一种颜色着色,因此它不起作用。我基于标准
quakes
数据集,需要根据
depth>300
条件使用不同的颜色。我尝试使用
lapply
但不确定我是否正确执行:
lapply(if(coords$depth > 300) 'red' else 'green',htmltools::HTML)
。不管怎样,你知道如何让它成为可能吗?

library(shiny)
library(leaflet)
library(dplyr)
library(sf)
library(htmlwidgets)


ui <- fluidPage(
   leafletOutput("map")
)

server <- function(input, output, session) {
   
   coords <- quakes %>%
      sf::st_as_sf(coords = c("long","lat"), crs = 4326)

     output$map <- leaflet::renderLeaflet({
     leaflet::leaflet() %>%         
       leaflet::addTiles() %>%
       leaflet::setView(172.972965,-35.377261, zoom = 4) %>%
       leaflet::addCircleMarkers(
         data = coords,
         stroke = FALSE,
         color = if(coords$depth > 300) 'red' else 'green',
         radius = 6)
   })
}

shinyApp(ui, server)
r shiny r-leaflet
1个回答
3
投票
library(tidyverse)
library(leaflet)

data(quakes)

quakes[1:20, ] %>%
  leaflet() %>%
  addTiles() %>%
  addCircleMarkers(~long, ~lat,
    popup = ~ as.character(mag),
    label = ~ as.character(mag),
    color = ~ ifelse(depth > 300, "red", "green")
  )

enter image description here

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