I'm fairly new to leaflet and mapping in R. I'm trying to visualize the traffic volume for certain multilinestring in R. The closest answer I found was:
How to plot MULTILINESTRING in leaflet addPolylines?
But I want to map those multilinestring based on their volumes or counts. My multilinestring data were originally in characters, so I used 'sf' library to convert them to sfc_multilinestring. You can find the original dataset here
My sample data:
data <- data.frame(
multilinestring = c("MULTILINESTRING ((-114.06036700906716 51.04831941917631, -114.05790835100508 51.04824965329041))", "MULTILINESTRING ((-114.06876825342002 50.96863425573366, -114.0714654457777 50.96864796962547))", "MULTILINESTRING ((-114.03372206187294 51.053232488239935, -114.03370889695204 51.05088210489753))"),
VOLUME = c(22000,5000,5000))
After converting to sfc_MULTILINESTRING
data$geom <- st_as_sfc(data$multilinestring)
I have tried the same code in the link (I shared above) but I can't figure out the color intensity.
leaflet((data$geom) %>%
addTiles() %>%
addPolygons()
The code above plots the multilinestring but I don't know how to change the color intensity of the multilinestrng based on their VOLUME.
This is what I want to get eventually (with my full dataset):
http://www.gisresources.com/free-us-traffic-count-data-use-maptitude-2018-mapping-software/
Here's my system and R version:
platform x86_64-w64-mingw32
arch x86_64
os mingw32
system x86_64, mingw32
status
major 4
minor 0.2
svn rev 78730
language R
version.string R version 4.0.2 (2020-06-22)
Here's how you can do this. A few things to point out:
st_as_sf()
, which converts the data frame to an sf object.colorNumeric()
)leaflet()
data <- data.frame(
multilinestring = c("MULTILINESTRING ((-114.06036700906716 51.04831941917631, -114.05790835100508 51.04824965329041))", "MULTILINESTRING ((-114.06876825342002 50.96863425573366, -114.0714654457777 50.96864796962547))", "MULTILINESTRING ((-114.03372206187294 51.053232488239935, -114.03370889695204 51.05088210489753))"),
VOLUME = c(22000,5000,5000)
)
data$geom <- st_as_sfc(data$multilinestring)
data <- st_as_sf(data)
pal <- colorNumeric(
palette = "Reds",
domain = data$VOLUME
)
leaflet(data) %>%
addTiles() %>%
addPolylines(color = ~pal(VOLUME))
Lastly, you'll want to customize your color palette, as the low-volume links show up in a pale color which is hard to see. See here for more guidance: https://rstudio.github.io/leaflet/colors.html
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.