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

tag5nh1u  于 2024-01-03  发布在  其他
关注(0)|答案(1)|浏览(184)

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

  1. # Import needed libraries
  2. library(tidyverse)
  3. library(leaflet)
  4. library(sf)
  5. # Create example dataset
  6. aa <- data.frame(
  7. state = c('Virginia','Virginia','North Carolina', 'North Carolina'),
  8. city = c('Richmond','Charlottesville', 'Raleigh', 'Charlotte'),
  9. lat = c(37.53,38.01,35.78,35.22),
  10. lon = c(-77.44,-78.47,-78.63,-80.84)) %>%
  11. st_as_sf(coords = c('lon', 'lat'), crs = 4269) %>%
  12. mutate(lat = st_coordinates(.)[, 2],
  13. lon = st_coordinates(.)[, 1])
  14. # Make map (this fills all points red)
  15. aa %>%
  16. leaflet(options = leafletOptions(attributionControl = F,
  17. zoomControl = F)) %>%
  18. addTiles() %>%
  19. addProviderTiles("Esri.WorldImagery") %>%
  20. setView(-78.47,
  21. 36.53,
  22. zoom = 7) %>%
  23. addCircleMarkers(lng = ~lon,
  24. lat = ~lat,
  25. fillColor = 'red',
  26. fillOpacity = 1,
  27. color = 'black',
  28. stroke = TRUE,
  29. weight = 2,
  30. radius = 5)

字符串


的数据

0sgqnhkj

0sgqnhkj1#

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

  1. # Import needed libraries
  2. library(tidyverse)
  3. library(leaflet)
  4. library(sf)
  5. pal <- leaflet::colorFactor(c("red", "blue"), domain = unique(aa$state))
  6. leaflet(options = leafletOptions(
  7. attributionControl = F,
  8. zoomControl = F
  9. )) %>%
  10. addTiles() %>%
  11. addProviderTiles("Esri.WorldImagery") %>%
  12. setView(-78.47,
  13. 36.53,
  14. zoom = 7
  15. ) %>%
  16. addCircleMarkers(
  17. lng = aa$lon,
  18. lat = aa$lat,
  19. label = aa$city,
  20. fillColor = pal(aa$state),
  21. fillOpacity = 1,
  22. color = "black",
  23. stroke = TRUE,
  24. weight = 2,
  25. radius = 5
  26. )

字符串


的数据

展开查看全部

相关问题