knitr::opts_chunk$set( collapse = TRUE, comment = "#>" )
This document is adapted from the Maps section of the Altair Example Gallery.
Our first step is to set up our environment:
library("altair") library("tibble") library("purrr") library("dplyr") vega_data <- import_vega_data()
It is not straightforward to preview the topological data, or the unemployment data:
vega_data$us_10m
data is in topoJSON, not a data framevega_data$unemployment
data is in an unparsed format.counties <- alt$topo_feature(vega_data$us_10m$url, "counties") unemp_data <- vega_data$unemployment$url
chart <- alt$Chart(counties)$ mark_geoshape()$ encode( color = "rate:Q" )$ transform_lookup( lookup = "id", from_ = alt$LookupData(unemp_data, "id", list("rate")) )$ project(type = "albersUsa")$ properties(width = 500, height = 300) chart
us <- vega_data$us_10m$url
airports <- vega_data$airports() glimpse(airports)
states <- alt$topo_feature(us, feature = "states") # US states background background <- alt$Chart(states)$ mark_geoshape( fill = "lightgray", stroke = "white" )$ properties(width = 500, height = 300)$ project("albersUsa") # airport positions on background points <- alt$Chart(airports)$ transform_aggregate( latitude = "mean(latitude)", longitude = "mean(longitude)", count = "count()", groupby = list("state") )$ mark_circle()$ encode( longitude = "longitude:Q", latitude = "latitude:Q", size = alt$Size('count:Q', title = "Number of Airports"), color = alt$value("steelblue"), tooltip = list("state:N","count:Q") )$ properties(title = 'Number of airports in US') chart <- (background + points) chart
glimpse(vega_data$population_engineers_hurricanes())
states <- alt$topo_feature(vega_data$us_10m$url, "states") source <- vega_data$population_engineers_hurricanes$url variable_list <- list("population", "engineers", "hurricanes") chart <- alt$Chart(states)$ mark_geoshape()$ encode( color = alt$Color(alt$`repeat`("row"), type = "quantitative") )$ transform_lookup( lookup = "id", from_ = alt$LookupData(source, "id", variable_list) )$ properties(width = 500, height = 300)$ project(type = "albersUsa")$ `repeat`(row = variable_list)$ resolve_scale(color = "independent") chart
Please see the Vega documentation for more details on the projections available.
countries <- alt$topo_feature(vega_data$world_110m$url, "countries") base <- alt$Chart(countries)$ mark_geoshape(fill = "#666666",stroke = "white")$ properties(width = 300, height = 180) projections <- list("equirectangular", "mercator", "orthographic", "gnomonic") # use purrr to fashion a facet_wrap charts <- map(projections, ~base$project(.x)$properties(title = .x)) chart <- (charts[[1]] | charts[[2]]) & (charts[[3]] | charts[[4]]) chart
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.