how to use colorNumeric within addCircles in leaflet

北慕城南 提交于 2019-12-13 20:13:42

问题


I have a leaflet map in which I have used addCircles, which are sized based on the population size of my data locations. I now want to color those circles based on the income of the population using colorNumeric. How do I use the population variable to determine my circle radii and simultaneously use the income variable to determine my color?

```{r}
library(leaflet)

leaflet()%>%
addTiles() %>%
addCircles(data = censusdata3, lng = ~Lon, lat = ~Lat, weight = 1, radius = ~households_estimate_total, popup = ~Geography, group = "Population", color) 
```

Data sample:

https://docs.google.com/spreadsheets/d/1Kw2daQk5ur-A3HbdJt7K7krFZ9Uh9Xg726sFRlQXIUM/edit?usp=sharing


回答1:


I basically just combined examples from two leaflet tutorial pages: https://rstudio.github.io/leaflet/colors.html and https://rstudio.github.io/leaflet/shapes.html

You can build a color palette with colorNumeric or one of the other palette functions in leaflet, and then color the circles the same way you would for a choropleth.

The csv file is just what's downloaded from your spreadsheet.

library(tidyverse)
library(leaflet)

censusdata3 <- read_csv("censusdata - ACS_16_5YR_S1901_with_ann.csv") %>%
    setNames(c("Geography", "Lon", "Lat", "total", "median_income", "median_income_moe", "mean_income", "mean_income_moe")) %>%
    mutate_at(vars(total:mean_income_moe), as.numeric)

color_pal <- colorNumeric(palette = "magma", domain = censusdata3$median_income, reverse = F)

leaflet()%>%
    addTiles() %>%
    addCircles(data = censusdata3, 
                         lng = ~Lon, lat = ~Lat, 
                         weight = 1, 
                         radius = ~total, 
                         popup = ~Geography,
                         color = ~color_pal(median_income)
                         ) 

Not to editorialize, but I'd also suggest scaling the radius by the square root of the population, not the population itself, because people perceive the difference in area of circles. The example for shapes includes a similar map where they use radius = ~sqrt(Pop) * 30.



来源:https://stackoverflow.com/questions/49951416/how-to-use-colornumeric-within-addcircles-in-leaflet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!