14  Diverging bar graphs

Graphs in this chapter use ggrewindr::theme_orbitz(), built from Orbitz, the 1997 drink with floating balls: a black background, a gold frame, gold and magenta ball marks, sand, maroon, and amber accents, and a Permanent Marker title.


Requirements:

✅ a categorical variable

✅ a numeric (continuous) variable

14.1 Description

If you have two proportions that contain positive and negative values, consider using diverging bars with geom_bar().

Unlike standard or stacked bar graphs, diverging bar graphs display positive and negative quantities on both sides of a reference or baseline value (zero in this example). Color, length and position are used to compare the quantities across categorical levels (and within variable values).

14.1.1 Vertical bars

For example, we can use the length of the bar from the reference line to compare Orbitz’s share across all weeks (i.e., comparing the magenta bars to each other).

14.1.2 Horizontal bars

We can also compare Surge vs. Orbitz within each week (i.e., compare the gold bar to the right of the line with the magenta bar to the left of it within each week).

14.2 Set up

PACKAGES

Install packages.

show/hide
library(ggplot2)
library(dplyr) # for data manipulation
library(tidyr) # for uncount()

DATA

Orbitz hit shelves in 1997 with colorful gel balls floating in a clear, fruity drink. Kids bought it once to see the balls, and then most of them went back to Surge. We’ll simulate a weekly lunchroom survey of 400 kids over the seven weeks after Orbitz arrived, asking which drink they bought that week: Surge, Orbitz, or something else (Other).

Surge’s chance of being picked grows each week as the novelty wears off (p_surge), Orbitz gets what’s left of 80% (p_orbitz), and Other stays at 20%. For each kid, runif() draws a number between 0 and 1, and case_when() turns that number into a choice using the week’s probabilities. Then we keep Surge and Orbitz, calculate each one’s share of the 400 kids, and make Orbitz’s share negative so it points down. Setting the seed with set.seed() means you’ll get the same 2,800 answers every time you run the code below.

show/hide
set.seed(1993) # same survey answers every time the code runs
lunchroom_survey <- tibble(week = 1:7) |> # seven weeks of surveys
  mutate(
    p_surge = 0.8 * plogis(-2 + 0.6 * (week - 1)), # Surge's share climbs each week
    p_orbitz = 0.8 - p_surge # Orbitz gets the rest of the 80% (the other 20% pick something else)
    ) |>
  tidyr::uncount(400, .id = "kid") |> # 400 kids answer each week
  mutate(
    u = runif(n()), # a random number between 0 and 1 for each kid
    choice = case_when(
      u < p_surge ~ "Surge", # below Surge's share
      u < p_surge + p_orbitz ~ "Orbitz", # inside Orbitz's share
      TRUE ~ "Other" # everything else
      )
    ) |>
  select(week, kid, choice)
orbitz_diverg <- lunchroom_survey |>
  filter(choice != "Other") |> # keep only the two drinks
  count(week, choice) |> # kids picking each drink each week
  mutate(
    share = n / 400, # share of all 400 kids
    share = if_else(choice == "Orbitz", -share, share), # Orbitz bars point down
    choice = factor(choice, levels = c("Surge", "Orbitz")),
    week = factor(week) # each week is a category
    )
glimpse(orbitz_diverg)
#> Rows: 14
#> Columns: 4
#> $ week   <fct> 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, …
#> $ choice <fct> Orbitz, Surge, Orbitz, Surge, Orb…
#> $ n      <int> 275, 30, 244, 65, 219, 94, 181, 1…
#> $ share  <dbl> -0.6875, 0.0750, -0.6100, 0.1625,…

14.3 Distribution

A diverging bar graph puts two shares back to back, so the question it answers is “how do these two groups trade places?” Here, every kid picks exactly one drink each week, so a gain for Surge has to come from somewhere. Below we’ll move from the kids, to a picture, to the formula.

COUNT IT

Start with the first ten kids surveyed in week 1.

show/hide
head(lunchroom_survey$choice, 10)
#>  [1] "Orbitz" "Surge"  "Orbitz" "Orbitz" "Orbitz"
#>  [6] "Orbitz" "Orbitz" "Orbitz" "Other"  "Surge"

Seven of these ten kids bought Orbitz, two bought Surge, and one bought something else. Counting every kid in every week shows the trade: Orbitz’s count falls each week while Surge’s climbs, and Other stays between about 60 and 100.

show/hide
lunchroom_survey |>
  count(week, choice) |>
  tidyr::pivot_wider(names_from = choice, values_from = n)

DRAW IT

A bar model shows each week’s 400 kids as one bar split three ways. Reading up from week 1, the Surge part grows, the Orbitz part shrinks, and the Other part barely moves.

show/hide
lunchroom_survey |>
  count(week, choice) |>
  mutate(choice = factor(choice,
    levels = c("Surge", "Orbitz", "Other"))) |>
  ggplot(aes(x = n, y = factor(week), fill = choice)) +
  geom_col(position = position_stack(reverse = TRUE)) +
  labs(x = "Kids", y = "Week", fill = "Drink")

The diverging bar graph below takes the Surge and Orbitz parts of each bar and points them in opposite directions from zero. The points mark the shares we built into the simulation. The two bars are the same length somewhere between weeks 4 and 5, which is where the two drinks traded places.

show/hide
expected_shares <- tibble(week = 1:7) |>
  mutate(Surge = 0.8 * plogis(-2 + 0.6 * (week - 1)),
         Orbitz = -(0.8 - Surge),
         week = factor(week)) |>
  tidyr::pivot_longer(-week, names_to = "choice", values_to = "share")

ggplot(data = orbitz_diverg, aes(x = week, y = share)) +
  geom_bar(aes(fill = choice), stat = "identity", width = .5) +
  geom_point(data = expected_shares, size = 2.5) +
  geom_hline(yintercept = 0) +
  scale_y_continuous(limits = c(-1, 1), labels = scales::percent) +
  labs(x = "Week", y = "Share of kids", fill = "Drink")

NAME IT

Each kid’s answer is a single draw from three choices, so each week’s counts follow a multinomial distribution:

\[ (N_{\text{Surge}}, N_{\text{Orbitz}}, N_{\text{Other}}) \sim \text{Multinomial}\left(400, \; (p_t, \; 0.8 - p_t, \; 0.2)\right) \]

\[ p_t = 0.8 \times \text{logistic}\left(-2 + 0.6\,(t - 1)\right) \]

The logistic function (plogis()) gives Surge’s share an S shaped climb: slow at first, fastest in the middle, then leveling off. Surge and Orbitz split the same 80%, so their bars are the same length when \(p_t = 0.4\). That happens when \(-2 + 0.6\,(t - 1) = 0\), or \(t \approx 4.3\).

Each simulated share wobbles around its point by about \(\sqrt{p(1 - p) / 400}\), which is never more than 2.5 percentage points. That’s why the bars land so close to the points. Try changing the 0.6 in plogis() and the crossover moves earlier (larger values) or later (smaller values).

CHANGE IT

So far the graph shows what we expect: the kids who drop Orbitz pick up Surge, so the two bars trade places. Now we’ll change where those kids go.

Suppose Surge never gains a single fan and stays at 30% every week. The kids who tire of the floating balls switch to other drinks instead (Snapple, Fruitopia, or plain milk). Orbitz still falls from 60% to 15%, and Other grows from 10% to 55%. We’ll keep the same 400 kids, the same seven weeks, and the same seed.

show/hide
set.seed(1993) # same seed as above
lunchroom_switch <- tibble(week = 1:7) |>
  mutate(
    p_surge = 0.3, # Surge stays flat
    p_orbitz = 0.6 - 0.075 * (week - 1) # Orbitz falls from 60% to 15%
    ) |>
  tidyr::uncount(400, .id = "kid") |>
  mutate(
    u = runif(n()),
    choice = case_when(
      u < p_surge ~ "Surge",
      u < p_surge + p_orbitz ~ "Orbitz",
      TRUE ~ "Other" # grows as Orbitz falls
      )
    ) |>
  select(week, kid, choice)
orbitz_switch <- lunchroom_switch |>
  filter(choice != "Other") |>
  count(week, choice) |>
  mutate(
    share = n / 400,
    share = if_else(choice == "Orbitz", -share, share),
    choice = factor(choice, levels = c("Surge", "Orbitz")),
    week = factor(week)
    )
lunchroom_switch |>
  count(week, choice) |>
  tidyr::pivot_wider(names_from = choice, values_from = n)

Below we redraw the same diverging bar graph with the new survey.

show/hide
ggplot(data = orbitz_switch, aes(x = week, y = share)) +
  geom_bar(aes(fill = choice), stat = "identity", width = .5) +
  geom_hline(yintercept = 0) +
  scale_y_continuous(limits = c(-1, 1), labels = scales::percent) +
  labs(x = "Week", y = "Share of kids", fill = "Drink")

The graph tells the same story as before: Orbitz’s bars shrink, and by week 6 Surge’s bar is the longer one. It looks like Surge won the lunchroom.

But Surge sold to between 110 and 135 kids every week. Orbitz fell from 235 kids to 58, and nearly all of them went to Other. That group grew from 50 kids to 232, the biggest group by week 7. The graph has no bar for it.

A diverging bar graph only shows the two groups we put on it. When those two don’t add up to the whole, the crossover can look like a trade that never happened. I’ve found it’s worth checking the group we dropped before reading two bars as winner and loser. If it changes, give it a bar or put its share in the subtitle.

14.4 Grammar

CODE

  • Create labels with labs()

  • Initialize the graph with ggplot() and provide data

  • Map the week to the x and share to the y

  • Inside geom_bar()

    • map choice to fill

    • use stat = "identity" and width = .5

  • Add scale_y_continuous() to manually set the limits and format the axis with scales::percent

show/hide
labs_geom_bar_diverg <- labs(
  title = "Orbitz vs. Surge",
  caption = "Simulated data",
  subtitle = "Drink 400 kids bought each week in 1997",
  x = "Week",
  y = "Share of kids",
  fill = "Drink")
ggp2_bars_diverg <- ggplot(
  data = orbitz_diverg,
    aes(x = week, y = share)) +
  geom_bar(aes(fill = choice),
    stat = "identity", width = .5) +
  scale_y_continuous(limits = c(-1, 1),
    labels = scales::percent)

ggp2_bars_diverg +
  labs_geom_bar_diverg

GRAPH

14.5 More info

For vertically arranged bars, we switch the x and y axis variables.

14.5.1 Vertically arranged bars


  • Create labels with labs()

  • Map the share to the x and week to the y

  • Inside geom_bar()

    • map choice to fill

    • use stat = "identity" and width = .5

  • Add scale_x_continuous() to manually set the limits and format the axis with scales::percent

show/hide
labs_geom_bar_diverg_vert <- labs(
  title = "Orbitz vs. Surge",
  caption = "Simulated data",
  subtitle = "Drink 400 kids bought each week in 1997",
  x = "Share of kids",
  y = "Week",
  fill = "Drink")
ggp2_bar_diverg_vert <- ggplot(
  data = orbitz_diverg,
      aes(x = share, y = week)) +
  geom_bar(
      aes(fill = choice),
        stat = "identity", width = .5) +
  scale_x_continuous(limits = c(-1, 1),
        labels = scales::percent)
ggp2_bar_diverg_vert +
  labs_geom_bar_diverg_vert