R语言 按组更改瓣叶标记填充颜色

tag5nh1u  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(151)

在下面的示例中,我的城市位于传单Map上。我希望弗吉尼亚州的城市的填充颜色为黄色,北卡罗来纳州的城市的填充颜色为绿色。如何在leafletMap上按组设置圆圈标记的填充颜色?
例如

# Import needed libraries
library(tidyverse)
library(leaflet)
library(sf)

# Create example dataset
aa <- data.frame(
  state = c('Virginia','Virginia','North Carolina', 'North Carolina'),
  city = c('Richmond','Charlottesville', 'Raleigh', 'Charlotte'),
  lat = c(37.53,38.01,35.78,35.22),
  lon = c(-77.44,-78.47,-78.63,-80.84)) %>%
  st_as_sf(coords = c('lon', 'lat'), crs = 4269) %>%
  mutate(lat = st_coordinates(.)[, 2],
         lon = st_coordinates(.)[, 1])

# Make map (this fills all points red)
aa %>%
  leaflet(options = leafletOptions(attributionControl = F,
                                 zoomControl = F)) %>%
  addTiles() %>%
  addProviderTiles("Esri.WorldImagery") %>%
  setView(-78.47,
          36.53,
          zoom = 7) %>%
  addCircleMarkers(lng = ~lon,
                   lat = ~lat,
                   fillColor = 'red',
                   fillOpacity = 1,
                   color = 'black',
                   stroke = TRUE,
                   weight = 2,
                   radius = 5)

字符串


的数据

0sgqnhkj

0sgqnhkj1#

对于离散变量,您可以使用leaflet::colorFactor创建一个调色板。然后可以使用该调色板根据state列分配fillColor

# Import needed libraries
library(tidyverse)
library(leaflet)
library(sf)

pal <- leaflet::colorFactor(c("red", "blue"), domain = unique(aa$state))

leaflet(options = leafletOptions(
  attributionControl = F,
  zoomControl = F
)) %>%
  addTiles() %>%
  addProviderTiles("Esri.WorldImagery") %>%
  setView(-78.47,
    36.53,
    zoom = 7
  ) %>%
  addCircleMarkers(
    lng = aa$lon,
    lat = aa$lat,
    label = aa$city,
    fillColor = pal(aa$state),
    fillOpacity = 1,
    color = "black",
    stroke = TRUE,
    weight = 2,
    radius = 5
  )

字符串


的数据

相关问题