Chapter 7 leaflet
and mapview
maps
This exercise will introduce construction of a Leaflet map using the leaflet
package. Also simple interface uses the mapview::mapview()
function, which automatically adds the OpenStreetMap background, uses pre-loaded colors, and with the legend = TRUE
option also adds a map legend.
mapview(nhood_pov, zcol = "pct_pov", legend = TRUE)
We will now build up a map using leaflet()
for a bit more control.
# CRS
<- nhood_pov %>% st_transform(4326)
nhood_pov_4326
# make a label with the count of persons, persons below poverty, and % poverty
$mylab <- sprintf(
nhood_pov_4326"n_pov=%s<br>n=%s<br>%s<br>",
round(nhood_pov_4326$n_pov, 0),
round(nhood_pov_4326$n, 0),
paste("pov=", nhood_pov_4326$pct_pov, "%", sep = "")
)
<- leaflet(data = nhood_pov_4326) %>%
l addPolygons(popup = ~mylab, weight = 2) %>%
addTiles()
l
Let’s change the labels to include neighborhood name and % poverty, add choropleth fill and a legend:
# CRS
<- nhood_pov %>% st_transform(4326)
nhood_pov_4326
<- colorQuantile(palette = "viridis", domain = nhood_pov_4326$pct_pov, n = 4)
mypalette
# make a label with the count of persons, persons below poverty, and % poverty
$mylab <- sprintf(
nhood_pov_4326"%s<br>%s<br>",
$gen_alias,
nhood_pov_4326paste("pov=", nhood_pov_4326$pct_pov, "%", sep = "")
)
<- leaflet(data = nhood_pov_4326) %>%
l addPolygons(
popup = ~mylab,
weight = 2,
fillColor = ~ mypalette(pct_pov),
opacity = 0.7
%>%
) addTiles() %>%
addLegend(pal = mypalette, values = ~pct_pov, opacity = 0.7, title = "% below poverty", position = "bottomleft")
l
Finally, add the hospitals with a label that will display when hovering over the point marker.
# CRS
<- nhood_pov %>% st_transform(4326)
nhood_pov_4326
# hospitals
<- st_read(file.path(mydatadir, "medical_facilities", "medical_facilities.shp"), quiet = TRUE) %>% st_transform(4326)
hospitals
<- colorQuantile(palette = "viridis", domain = nhood_pov_4326$pct_pov, n = 4)
mypalette
# make a label with the count of persons, persons below poverty, and % poverty
$mylab <- sprintf(
nhood_pov_4326"<u>%s</u><br>%s<br>",
$gen_alias,
nhood_pov_4326paste("pov=", nhood_pov_4326$pct_pov, "%", sep = "")
)
<- leaflet(data = nhood_pov_4326) %>%
l addPolygons(
popup = ~mylab,
weight = 2,
fillColor = ~ mypalette(pct_pov),
opacity = 0.7
%>%
) addTiles() %>%
addLegend(pal = mypalette, values = ~pct_pov, opacity = 0.7, title = "% below poverty", position = "bottomleft")
<- addCircleMarkers(
l map = l,
data = hospitals,
radius = 5,
weight = 1,
opacity = 0.9,
fillOpacity = 0.5,
label = ~ABB_NAME
)
l
7.1 Conclusion
R makes it easy to create web-ready maps based on the leaflet
and mapview
packages. See the documentation and other tutorials for additional information.