how to use colorNumeric within addCircles in leafl

2019-08-17 01:04发布

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条回答
仙女界的扛把子
2楼-- · 2019-08-17 01:58

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.

查看更多
登录 后发表回答