
34 Instance chart
theme_gushers()
Graphs in this chapter use ggrewindr::theme_gushers(), built from Fruit Gushers: a white plate background, a red frame and title, red, green, teal, orange, and pink fruit snack marks, and a Patrick Hand title.
34.1 Description
An instance chart (or instance graph) displays frequencies (or ‘instances’) of different categorical values over time.
The time dimension is placed on the x and each separate categorical item is placed on the y-axis. The instances are typically represented using the vertical hashes from geom_point() (i.e., shape 124 or the ‘pipe’ "|").
Transparency (alpha) and color are also used to represent different categorical levels and counts.
34.2 Set up
PACKAGES
Install packages.
show/hide
library(ggplot2)
library(dplyr) # for data manipulation
library(tidyr) # for expand_grid()DATA
Fruit Gushers arrived in 1991: fruit snacks with a liquid center, sold with commercials where a kid’s head turned into a giant piece of fruit. Fruit snacks were already the currency of the lunch table, and a new Gushers flavor made its fruit worth more.
We’ll simulate how many packs of each flavor were traded at one lunch table every year from 1980 to 2005. Each flavor in snack_flavors has an average number of trades per year before its pretend Gushers debut and an average after it (berry punch shows up in 1992, sour apple in 1998, and mystery in 2001). rpois() draws each year’s count (n) from the matching average. Setting the seed with set.seed() means you’ll get the same 208 flavor years every time you run the code below.
show/hide
snack_flavors <- tibble(
flavor = c("Strawberry", "Lime", "Blue raspberry", "Orange", # eight Gushers flavors
"Watermelon", "Berry punch", "Sour apple", "Mystery"),
before = c(4, 0.3, 1, 1.5, 0.2, 1, 0.05, 0.05), # average yearly trades before the debut
after = c(8, 1.5, 4, 1.5, 0.8, 1.5, 2, 3), # average yearly trades after the debut
debut = c(1991, 1991, 1991, 1991, 1991, 1992, 1998, 2001) # pretend debut year for each flavor
)
set.seed(1993) # same trades every time the code runs
lunch_trades <- expand_grid(year = 1980:2005, snack_flavors) |> # every flavor in every year
mutate(
flavor = factor(flavor, levels = snack_flavors$flavor), # keep the order above
avg_n = if_else(year < debut, before, after), # pick the average for that year
n = rpois(n(), lambda = avg_n) # number of trades that year
) |>
select(year, flavor, debut, avg_n, n)
glimpse(lunch_trades)
#> Rows: 208
#> Columns: 5
#> $ year <int> 1980, 1980, 1980, 1980, 1980, 198…
#> $ flavor <fct> Strawberry, Lime, Blue raspberry,…
#> $ debut <dbl> 1991, 1991, 1991, 1991, 1991, 199…
#> $ avg_n <dbl> 4.00, 0.30, 1.00, 1.50, 0.20, 1.0…
#> $ n <int> 3, 0, 0, 2, 0, 1, 0, 0, 6, 0, 1, …An instance chart only shows the years a flavor was traded, so we’ll filter out the years with no trades and store the rest in gushers_trades.
show/hide
gushers_trades <- lunch_trades |>
filter(n > 0) # keep only the years with at least one trade
glimpse(gushers_trades)
#> Rows: 128
#> Columns: 5
#> $ year <int> 1980, 1980, 1980, 1981, 1981, 198…
#> $ flavor <fct> Strawberry, Orange, Berry punch, …
#> $ debut <dbl> 1991, 1991, 1992, 1991, 1991, 199…
#> $ avg_n <dbl> 4.0, 1.5, 1.0, 4.0, 1.0, 1.5, 1.0…
#> $ n <int> 3, 2, 1, 6, 1, 3, 3, 2, 1, 3, 1, …34.3 Distribution
An instance chart is built from two things: whether a flavor shows up in a given year (the tick), and how many times it shows up (the tick’s transparency). The empty spaces between the ticks matter just as much as the ticks, and the number of empty spaces depends on how popular the flavor is. Below we’ll move from the counts, to a picture, to the formula.
COUNT IT
Start with lime in the five years before and after Gushers arrived.
show/hide
lunch_trades |>
filter(flavor == "Lime", year >= 1986, year <= 1995)Before 1991, most years have no lime trades at all. Below we count the years with zero trades (zero_years) for each flavor, before and after its debut.
show/hide
zero_counts <- lunch_trades |>
mutate(era = if_else(year < debut, "before", "after")) |>
group_by(flavor, era) |>
summarise(years = n(), zero_years = sum(n == 0), .groups = "drop") |>
pivot_wider(names_from = era, values_from = c(years, zero_years)) |>
select(flavor, years_before, zero_years_before,
years_after, zero_years_after)
zero_countsLime went 8 of 11 years without a trade before Gushers, and only 3 of 15 years after it. Strawberry, the most popular flavor, never had a year without a trade.
DRAW IT
The graph below draws lime’s yearly counts as bars (including the zeros) and the same years as instance ticks across the bottom. Every gap in the ticks is a year with a bar of height zero.
show/hide
lime <- lunch_trades |>
filter(flavor == "Lime")
ggplot(lime, aes(x = year)) +
geom_col(aes(y = n), fill = "#4E6B44") +
geom_point(data = filter(lime, n > 0), aes(y = -0.5),
shape = 124, size = 5, color = "#D01D27") +
geom_vline(xintercept = 1990.5, linetype = "dashed") +
annotate("text", x = 1990.3, y = max(lime$n), label = "Gushers come out", hjust = 1) +
labs(title = "Lime trades each year", x = "Year", y = "Lime trades")
NAME IT
Each yearly count follows a Poisson distribution with the average for that flavor and era:
\[ n_{\text{flavor, year}} \sim \text{Poisson}(\lambda), \quad P(n = 0) = e^{-\lambda} \]
The chance of an empty year depends only on \(\lambda\). Before Gushers, lime’s average is 0.3 trades a year, so \(P(n = 0) = e^{-0.3} \approx 0.74\), and we’d expect about \(11 \times 0.74 \approx 8.1\) empty years out of 11. After Gushers, the average jumps to 1.5, so \(P(n = 0) = e^{-1.5} \approx 0.22\) and we’d expect about 3.3 empty years out of 15.
Strawberry averages 8 trades a year after Gushers, so an empty year has a chance of \(e^{-8} \approx 0.0003\) (practically never). That’s why rare flavors look like scattered ticks and popular flavors look like solid lines. Try changing lime’s after value to 5 and its row fills in.
34.4 Grammar
CODE
Create labels with
labs()Initialize the graph with
ggplot()and providedataMap
yeartox,flavortoy, andflavortocolorAdd
geom_point(), mapntoalpha, and set theshapeto124andsizeto5Most years have only a few trades, so we raise the lightest
alphawithscale_alpha_continuous(range = c(0.35, 1))(otherwise the faint ticks disappear)Remove the
colorlegend withguides()(the flavors are already on theyaxis)
show/hide
labs_inst_gushers <- labs(
title = "Fruit Gushers",
caption = "Simulated data",
subtitle = "Fruit snack trades at one lunch table, 1980 - 2005",
x = "Year",
y = "Flavor",
alpha = "Trades per year")
ggp2_inst_gushers <- ggplot(data = gushers_trades,
mapping = aes(x = year,
y = flavor,
color = flavor)) +
geom_point(aes(alpha = n),
shape = 124,
size = 5) +
scale_alpha_continuous(range = c(0.35, 1)) +
guides(color = "none")
ggp2_inst_gushers +
labs_inst_gushersGRAPH

34.5 More info
34.5.1 Color with cut_interval()
ggplot2 has three great functions for splitting numerical variables into intervals or widths: cut_interval(), cut_number(), and cut_width(). We’ll use cut_interval() to create an n_range variable, which splits the yearly counts (n) into intervals based on the length argument.
show/hide
gushers_trades_range <- gushers_trades |>
mutate(
n_range = ggplot2::cut_interval(x = n, length = 3) # group trade counts into bins 3 wide
)
gushers_trades_range |>
count(n_range) # rows in each binBelow we can see the count ranges have been built with the interval notation: "(a,b]"
- Most of the ticks fall in the lowest range, and every count above 9 belongs to strawberry after Gushers arrived.
show/hide
labs_inst_gushers_range <- labs(
title = "Fruit Gushers",
caption = "Simulated data",
subtitle = "Fruit snack trades at one lunch table, 1980 - 2005",
x = "Year",
y = "Flavor",
color = "Trades per year")
ggp2_inst_gushers_range <- ggplot(data = gushers_trades_range,
mapping = aes(x = year,
y = flavor,
color = n_range)) +
geom_point(aes(alpha = n),
shape = 124,
size = 4) +
scale_alpha_continuous(range = c(0.35, 1)) +
guides(alpha = "none") # the color key already shows the trade counts
ggp2_inst_gushers_range +
labs_inst_gushers_range
34.5.2 Facets with cut_number()
To demonstrate facets, we’ll create two other variables: year_range and group:
year_rangeusesggplot2::cut_number()to split theyearinto three groups with about the same number of ticks in each, then we build a label for each group from its first and last yeargroupis a factor variable with two levels:"Single fruit"and"Berry blends"(blue raspberry and berry punch)
show/hide
gushers_trades_fct <- gushers_trades |>
mutate(
year_grp = ggplot2::cut_number(year, n = 3, labels = FALSE) # three groups of years with similar counts
) |>
group_by(year_grp) |>
mutate(year_range = paste(min(year), "-", max(year))) |> # label each group with its years
ungroup() |>
mutate(
year_range = factor(year_range, levels = unique(year_range[order(year)])), # earliest to latest
group = if_else(flavor %in% c("Blue raspberry", "Berry punch"), "Berry blends", "Single fruit"), # two flavor groups
group = factor(group, levels = c("Single fruit", "Berry blends"))
)Below we can see how many flavor years (with at least one trade) fall in each cell of the cross-table of year_range and group
show/hide
gushers_trades_fct |>
count(year_range, group) |>
pivot_wider(names_from = group,
values_from = n)In the graph, the panel labels come from the levels of year_range, so the subtitle only needs the first and last year of all the trades.
We can also change the
shapeused ingeom_point()to the pipe character ("|")facet_grid()puts the flavor groups in rows and the year ranges in columns. Withscales = "free", each row keeps only its own flavors (so they line up across the row). Each column also picks its ownxbreaks, so we set them every five years withscale_x_continuous()
show/hide
labs_inst_gushers_facet <- labs(
title = "Fruit Gushers",
caption = "Simulated data",
subtitle = "Fruit snack trades at one lunch table, 1980 - 2005",
x = "Year",
y = "Flavor")
ggp2_inst_gushers_facet <- ggplot(gushers_trades_fct,
mapping = aes(x = year,
y = flavor)) +
geom_point(aes(alpha = n, color = flavor),
shape = "|",
size = 3,
show.legend = FALSE) +
scale_x_continuous(breaks = seq(1980, 2005, by = 5)) +
scale_alpha_continuous(range = c(0.35, 1)) +
facet_grid(group ~ year_range,
scales = "free")
ggp2_inst_gushers_facet +
labs_inst_gushers_facet