knitr::opts_chunk$set( collapse = TRUE, comment = "#>", message = FALSE, warning = FALSE )
There is a ton of spatial data on the City of Toronto Open Data Portal. Spatial resources are retrieved the same way as all other resources, by using get_resource()
, and may require the sf
package.
We can look at the locations of EarlyON Child and Family Centres in Toronto. As the portal describes, these centres offer free programs to caregivers and children, providing programs to strengthen relationships, support education, and foster healthy child development. The result of pulling this data in through the package is an sf
object with WGS84 projection.
library(opendatatoronto) library(dplyr) earlyon_centres <- search_packages("EarlyON Child and Family Centres") %>% list_package_resources() %>% filter(name == "EarlyON Child and Family Centres Locations - geometry - 4326.zip") %>% get_resource() earlyon_centres
If we want to plot this data on a map of Toronto, a shapefile to map the different neighbourhoods of Toronto is also available from the portal:
neighbourhoods <- list_package_resources("https://open.toronto.ca/dataset/neighbourhoods/") %>% filter(name == "Neighbourhoods - 4326.zip") %>% get_resource() neighbourhoods[c("AREA_NA7", "geometry")]
Then, we can plot the EarlyON centres along with a map of Toronto:
library(ggplot2) ggplot() + geom_sf(data = neighbourhoods) + geom_sf(data = earlyon_centres) + theme_void()
We may also wish to do something like analyze how many EarlyON centres there are in each neighbourhood. We can count by neighbourhood, using the sf
package to join the two datasets, then dplyr
to summarise, and finally ggiraph
to create an interactive visualization, replacing geom_sf
with geom_sf_interactive
and supplying a tooltip:
library(sf) library(dplyr) library(ggiraph) library(glue) earlyon_by_neighbourhood <- neighbourhoods %>% st_join(earlyon_centres) %>% group_by(neighbourhood = AREA_NA7) %>% summarise(n_earlyon = n_distinct(program5, na.rm = TRUE)) %>% mutate(tooltip = glue(("{neighbourhood}: {n_earlyon}"))) p <- ggplot() + geom_sf_interactive(data = earlyon_by_neighbourhood, aes(fill = n_earlyon, tooltip = tooltip)) + theme_void() girafe(code = print(p))
This shows us, for example, that there are 9 EarlyON Centres in West Hill, 5 in Kensington-Chinatown, and 5 in South Riverdale:
earlyon_by_neighbourhood %>% as_tibble() %>% select(neighbourhood, n_earlyon) %>% arrange(-n_earlyon) %>% head()
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.