Leaflet圆形标记未匹配colorFactor调色板问题求助
Leaflet圆形标记颜色与等级不匹配的修复方案
问题诊断
你的代码中存在两个关键问题导致颜色与severity等级对应混乱:
Label引用错误
代码里label = acc$severity直接调用了原始全量数据集的severity字段,但前面已经通过filter对数据做了筛选,这会让标记的label和实际渲染的点位错位——你看到的label并非当前点位的真实severity,进而误以为颜色匹配错误。数据与调色板domain的一致性验证缺失
需确认acc$severity的实际取值,是否和你定义调色板时的domain = c("1. Fatal", "2. Serious", "3. Slight")完全一致(包括空格、标点、大小写),如果数据里的取值有差异,colorFactor会无法正确映射。
修复后的代码
library(dplyr) library(tidyverse) library(leaflet) library(sf) library(shiny) library(leafpop) acc <- read.csv('acc.csv') names(acc) <- tolower(names(acc)) # 可提前打印验证数据取值:print(unique(acc$severity)) pal <- colorFactor(c("red", "navy", "green"), domain = c("1. Fatal", "2. Serious", "3. Slight")) acc <- acc %>% st_as_sf(coords = c("easting", "northing"), crs = 27700) %>% st_transform('+proj=longlat +datum=WGS84') %>% mutate(lon = sf::st_coordinates(.)[,1], lat = sf::st_coordinates(.)[,2]) output$test <- renderLeaflet({ # 将过滤后的数据存为临时变量,避免引用错位 filtered_acc <- acc %>% filter(local_auth %in% input$box_local_auth) %>% filter(month %in% input$box_month) %>% filter(year %in% input$box_year) %>% filter(severity %in% input$box_severity) filtered_acc %>% leaflet() %>% addTiles() %>% addCircleMarkers( radius = 5, color = ~pal(severity), # 引用当前过滤数据集的severity字段 label = ~severity, # 弹窗内容对应过滤后的数据集 popup = popupTable(filtered_acc)) %>% addPolylines(data = map %>% filter(LAD23NM %in% input$box_local_auth), color = "blue", fillOpacity = 0) })
错误示例说明
- 示例1:标记颜色与显示的
severity等级完全不对应,严重等级的点位未显示定义的红色- 示例2:不同严重程度的点位颜色随机分布,无逻辑关联
内容的提问来源于stack exchange,提问作者Nick Curran
相关产品推荐
相关产品推荐

