gapminder-animate.Rmd
This example is an adaptation of the interactive global development scatter plot from the Vega-Lite documentation. We create two selection objects: the first is a slider that is bound to the years in the gapminder data, and another that corresponds to hovering over nearest points.
library(virgo)
library(gapminder)
slide_year <- select_bind(
year = input_slider("Year",
min = min(gapminder$year),
max = max(gapminder$year),
step = 5,
init = 1982)
)
nearest_country <- select_single(
fields = "country",
on = "mouseover",
empty = "none"
)
Next we initialise our graphic by creating a scatter plot for GDP against life expectancy, where the view is filtered by the current year selected in the slider. We then add lines, circles, and text marks that reveal the trajectory of a countries GDP per capita and life expectancy over time when you hover a point. Finally, we place the x-axis on a log scale.
gapminder %>%
vega(enc(x = gdpPercap, y = lifeExp), width = 400, height = 400) %>%
mark_point(
enc(color = continent, group = country),
selection = slide_year
) %>%
mark_line(
enc(
group = country,
order = year,
opacity = encode_if(nearest_country, 0.8, 0)
),
color = "#9e9ac8",
size = 4,
stroke_cap = "round"
) %>%
mark_circle(selection = nearest_country) %>%
mark_text(
enc(text = year),
selection = nearest_country,
color = "black",
dx = 12,
dy = 8
) %>%
scale_x(type = "log")