32  Stream plots

Graphs in this chapter use ggrewindr::theme_hypercolor(), built from Generra Hypercolor shirts: a deep purple background, a magenta frame, heat changing magenta, orange, purple, blue, green, and yellow marks, and a Cabin title.


Requirements:

✅ a categorical variable

✅ a numeric (continuous) variable

✅ a numeric (date) variable

32.1 Description

Stream graphs display how a numerical variable (typically on the y axis) changes over time (on the x axis) across levels of a categorical variable. These graphs are handy if the numerical value varies wildly (or isn’t always present) over the time measurement.

Categorical groups are differentiated by color layers, with the area of the layer representing the change in y value. In ggplot2, we can create stream graphs using ggstream.

32.2 Set up

PACKAGES

Install packages.

show/hide
remotes::install_github("davidsjoberg/ggstream")
library(ggstream)
library(ggplot2)
library(dplyr) # for data manipulation
library(tidyr) # for expand_grid()

DATA

The 90s were a decade of fads that showed up overnight and vanished just as fast. Slap bracelets were banned from schools, Hypercolor shirts changed color when you touched them, and Koosh balls and scrunchies were everywhere.

We’ll simulate the monthly sales (in thousands) for four fads from 1990 through 1999. Each fad in fads gets a peak (the year it was most popular), a spread (how long it lasted, in years), and a total (how many it sold overall). The monthly average (avg_sales) follows a bell shaped curve around the peak, and rpois() draws the actual monthly sales. Setting the seed with set.seed() means you’ll get the same 120 months of sales every time you run the code below.

show/hide
fads <- tibble(
  fad = c("Slap bracelets", "Hypercolor", "Koosh balls", "Scrunchies"), # four early 90s fads
  peak = c(1990.8, 1991.5, 1992.5, 1994), # when each fad peaked
  spread = c(0.4, 0.6, 1.5, 2.2), # how long each fad lasted (in years)
  total = c(3000, 4000, 5000, 9000) # total sales over the decade
  )
set.seed(1991) # same monthly sales every time the code runs
fad_sales <- expand_grid(
  month = seq(as.Date("1990-01-01"), as.Date("1999-12-01"), by = "month"), # 120 months
  fads # every fad in every month
  ) |>
  mutate(
    fad = factor(fad, levels = fads$fad), # keep the order above
    t = lubridate::year(month) + (lubridate::month(month) - 1) / 12, # month as a decimal year
    avg_sales = total / 12 * dnorm(t, mean = peak, sd = spread), # bell shaped rise and fall
    sales = rpois(n(), lambda = avg_sales) # monthly sales around the curve
    ) |>
  select(month, fad, avg_sales, sales)
glimpse(fad_sales)
#> Rows: 480
#> Columns: 4
#> $ month     <date> 1990-01-01, 1990-01-01, 1990-…
#> $ fad       <fct> Slap bracelets, Hypercolor, Ko…
#> $ avg_sales <dbl> 33.744354, 9.737945, 27.632539…
#> $ sales     <int> 44, 11, 32, 24, 51, 18, 24, 22…

32.3 Distribution

A stream plot stacks each group’s values on top of one another and lets the stack flow over time. Each fad’s layer has its own shape: a quick spike for fads that burned out fast, and a long, low hump for fads that hung around. Below we’ll move from the monthly sales, to a picture, to the formula, and see where those shapes come from.

COUNT IT

Start with the first six months of Hypercolor sales in 1991.

show/hide
fad_sales |>
  filter(fad == "Hypercolor", month >= as.Date("1991-01-01")) |>
  head(6)

Sales wobble a little from month to month, but they climb toward the summer of 1991 right along with avg_sales. Below we total each fad’s sales and find its best month.

show/hide
fad_peaks <- fad_sales |>
  group_by(fad) |>
  summarise(total_sales = sum(sales),
            best_month = month[which.max(sales)],
            best_sales = max(sales))
fad_peaks

Scrunchies sold the most overall (8,748 thousand), but slap bracelets had the biggest single month (255 thousand). Selling the most and peaking the highest are two different things.

DRAW IT

The graph below draws each fad’s monthly sales as points and its avg_sales as a line. Every fad follows the same bell shaped curve. Slap bracelets and Hypercolor have narrow, tall bells, and scrunchies have a wide, short one.

show/hide
ggplot(fad_sales, aes(x = month, color = fad)) +
  geom_point(aes(y = sales), alpha = 1 / 2, size = 1) +
  geom_line(aes(y = avg_sales), linewidth = 1) +
  facet_wrap(~ fad, ncol = 2) +
  labs(x = "Month", y = "Sales (thousands)") +
  theme(legend.position = "none")

A stream plot stacks these four bells on top of each other (and centers the stack), which is why the stream bulges in the early 90s and thins out by the end of the decade.

NAME IT

The monthly sales are Poisson counts, and the average for each month follows the shape of a normal distribution over time:

\[ \text{sales}_t \sim \text{Poisson}(\lambda_t), \quad \lambda_t = \frac{\text{total}}{12} \times \frac{1}{\text{spread}\sqrt{2\pi}} \, e^{-\frac{(t - \text{peak})^2}{2 \, \text{spread}^2}} \]

Here we only borrow the normal curve for its shape (it describes when the sales happen, not a random variable). The area under the whole curve is the total, so the height of the peak is \(\frac{\text{total}}{12 \times \text{spread} \sqrt{2\pi}}\). Our ten years trim the tails, so the avg_sales we keep add up to a little less (2,947 of the 3,000 for slap bracelets).

Slap bracelets sold 3000 thousand over a spread of 0.4 years, so their peak is about 249 thousand a month. Scrunchies sold three times as much, but spread those sales over 2.2 years, so their peak is only about 136 thousand a month. Try changing the spread for scrunchies to 0.5 and watch their layer turn into a spike.

32.4 Grammar

CODE

  • Create labels with labs()

    • Use paste0() in the subtitle to automatically update the years when fad_sales changes
  • Initialize the graph with ggplot() and provide data

  • Map month to the x, sales to y, and fad to fill

  • Add the geom_stream() layer

  • Finally, move the legend with theme(legend.position = "bottom") and drop the y axis text with axis.text.y = element_blank(). The mirrored stream sits on both sides of 0, so half of those labels would show negative sales.

show/hide
labs_stream <- labs(
    title = "90s fads",
    caption = "Simulated data",
    subtitle =
        paste0("Monthly sales between ",
            format(min(fad_sales$month), "%Y"),
            " and ",
            format(max(fad_sales$month), "%Y")),
    x = "Month",
    y = "Sales (thousands)",
    fill = "Fad")

ggp2_stream <- ggplot(data = fad_sales,
    mapping = aes(x = month,
                  y = sales,
                  fill = fad)) +
    ggstream::geom_stream()
ggp2_stream +
    labs_stream +
    theme(legend.position = "bottom",
          axis.text.y = element_blank())

GRAPH

32.5 More info

The ggstream package has multiple arguments for adjusting the shape and look of the categorical levels (and text labels).

32.5.1 Type

  • Map fad to fill (wrapped in forcats::fct_rev())

  • We can adjust the look of the graph by setting the type argument in geom_stream()

    • type: change type from "mirror" (the default) to "proportional"
  • Adjust colors:

    • scale_fill_manual(): Add colors as a named vector to values
  • Finally, add the fill to the labels and move the legend with theme(legend.position = "bottom")

show/hide
fad_colors <- c("Slap bracelets" = "#FFE135",
                "Hypercolor" = "#E0218A",
                "Koosh balls" = "#2DBE60",
                "Scrunchies" = "#1F9BFF")
ggp2_stream_prp <- ggplot(data = fad_sales,
    mapping = aes(x = month,
                  y = sales,
                  fill = forcats::fct_rev(fad))) +
    ggstream::geom_stream(type = "proportional") +
    scale_y_continuous(labels = scales::percent) +
    scale_fill_manual(values = fad_colors)
ggp2_stream_prp +
    labs_stream +
    labs(y = "Share of sales", fill = "Fad") +
    theme(legend.position = "bottom")

The proportional stream shows each fad’s share of the month’s sales. Scrunchies take over the whole stream by the end of the decade, because their wide bell is the last one still selling.

32.5.2 Sorting

To change how the categorical areas are sorted, adjust the sorting argument to either "none", "onset", or "inside_out"

  • sorting: set the sorting method to "inside_out" in both ggstream::geom_stream() and ggstream::geom_stream_label()

  • type: change the type to "ridge" in both ggstream::geom_stream() and ggstream::geom_stream_label()

We can also add text labels using ggstream::geom_stream_label():

  • Map fad (wrapped in forcats::fct_rev()) to label globally

  • Inside ggstream::geom_stream_label():

    • map fad to color and set the size to 3

    • set n_grid to 1000 (the default grid of 100 points is smaller than our 120 months, which causes an error)

    • Keep the labels out of the legend with show.legend = FALSE (the fill legend stays)

Colors:

  • Use scale_fill_manual() to manually set the values using the named fad_colors vector

  • Use scale_color_manual() to make the labels white, except dark plum on the light yellow slap bracelets layer

  • Finally, add the fill to the labels and move the legend with theme(legend.position = "bottom")

show/hide
ggp2_stream_srt <- ggplot(data = fad_sales,
    mapping = aes(x = month,
                  y = sales,
                  fill = forcats::fct_rev(fad),
                  label = forcats::fct_rev(fad))) +
    ggstream::geom_stream(
        type = "ridge",
        sorting = "inside_out") +
    ggstream::geom_stream_label(
        type = "ridge",
        mapping = aes(color = forcats::fct_rev(fad)),
        sorting = "inside_out",
        size = 3,
        n_grid = 1000,
        show.legend = FALSE) +
    scale_fill_manual(values = fad_colors) +
    scale_color_manual(values = c("Slap bracelets" = "#2A0A3D",
                                  "Hypercolor" = "#FDF6FF",
                                  "Koosh balls" = "#FDF6FF",
                                  "Scrunchies" = "#FDF6FF"))

ggp2_stream_srt +
    labs_stream +
    labs(fill = "Fad") +
    theme(legend.position = "bottom")