class: center, middle, inverse, title-slide # Working with Geospatial Data ## Colors in Leaflet ### Ben Baumer ### SDS 192April 8, 2020(
http://beanumber.github.io/sds192/lectures/mdsr_geo_04-leaflet-colors.html
) --- class: center, middle, inverse # Colors in Leaflet --- ## You want colors to work like this, but... ```r library(macleish) library(leaflet) leaflet() %>% addTiles() %>% addPolygons(data = pluck(macleish_layers, "wetlands"), color = ~SHAPE_AREA, popup = ~IT_VALDESC) ```
--- ## Leaflet uses [**color palette functions**](https://rstudio.github.io/leaflet/colors.html) - For continuous variables: - `colorNumeric()` - `colorBin()` - `colorQuantile()` - For categorical variables: - `colorFactor()` - all take two arguments - `palette` (can be `RColorBrewer` or `viridis`) - `domain` (can be `NULL`) .footnote[https://rstudio.github.io/leaflet/colors.html] --- ## Step 1: define the color palette .footnote[https://rstudio.github.io/leaflet/colors.html] .pull-left[ ```r wetland_pal <- colorNumeric( palette = "viridis", domain = macleish_layers %>% pluck("wetlands") %>% pull(SHAPE_AREA) ) ``` - This is now a function that - takes an **area** - returns an HTML **color** ] -- .pull-right[ ```r wetland_pal(2000) ``` ``` ## [1] "#471164" ``` ```r wetland_pal(5000) ``` ``` ## [1] "#3D4D8A" ``` ] --- ## Why is all this necessary? - Helps control out of range values ```r macleish_layers %>% pluck("wetlands") %>% pull(SHAPE_AREA) %>% range() ``` ``` ## [1] 1302.77 17349.53 ``` ```r wetland_pal(2000) ``` ``` ## [1] "#471164" ``` ```r wetland_pal(100) ``` ``` ## Warning in wetland_pal(100): Some values were outside the color scale and will ## be treated as NA ``` ``` ## [1] "#808080" ``` --- ## Step 2: use the palette to map to color ```r leaflet() %>% addTiles() %>% addPolygons(data = pluck(macleish_layers, "wetlands"), color = ~wetland_pal(SHAPE_AREA), fillOpacity = 0.8, weight = 0.1, popup = ~IT_VALDESC) ```