9  Summary bar graphs

Graphs in this chapter use ggrewindr::theme_happymeal(), modeled on a McDonald’s Happy Meal box: red box, golden yellow marks, a cream plot area, and a Varela Round title.


Requirements:

✅ a numeric (continuous) variable

✅ a categorical variable

9.1 Description

Bar graphs can summarize data by showing a statistic for each category. The x-axis lists the categories, and the y-axis shows the values. They can include error bars to show variation or confidence intervals.

In ggplot2, we can create summary bar graphs with geom_col().

9.2 Set up

PACKAGES

Install packages.

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

DATA

McDonald’s ran a different Happy Meal toy promotion every few weeks in the late 90s. Some toys (like the 1997 Teenie Beanie Babies) sold out almost everywhere.

We’ll simulate 28 days of Happy Meal sales at one restaurant for four promotions. Each promotion gets its own daily sales rate (lambda). tidyr::uncount() creates one row per day, and rpois() draws the number sold. Then we average the daily sales for each promotion (avg_sold). Setting the seed with set.seed() means you’ll get the same 112 days every time you run the code below.

show/hide
set.seed(1997) # same 28 days of sales every time the code runs
happy_meals <- tibble(
  promotion = c("Teenie Beanie Babies", "Furby", # four Happy Meal promotions
                "Hot Wheels", "Inspector Gadget"),
  lambda = c(420, 310, 220, 180) # average Happy Meals sold per day
  ) |>
  tidyr::uncount(28, .id = "day") |> # 28 days of each promotion
  mutate(
    promotion = factor(promotion, levels = unique(promotion)), # keep the order above
    sold = rpois(n(), lambda = lambda) # daily sales around each average
    ) |>
  select(promotion, day, sold)
hm_sum_col <- happy_meals |>
  group_by(promotion) |> # one group per promotion
  summarise(avg_sold = mean(sold)) |> # average daily sales
  ungroup()
dplyr::glimpse(hm_sum_col)
#> Rows: 4
#> Columns: 2
#> $ promotion <fct> Teenie Beanie Babies, Furby, H…
#> $ avg_sold  <dbl> 417.6071, 309.3929, 229.5714, …

9.3 Distribution

A summary bar graph shows one statistic per group (here, the mean). Each bar hides 28 days of sales behind a single height. Before we trust the differences between bars, it’s worth knowing how much those days vary. Below we’ll move from the daily sales, to a picture, to the formula.

COUNT IT

Start with the first week of the Teenie Beanie Babies promotion.

show/hide
head(happy_meals, 7)

Daily sales bounce around between about 400 and 450, but they never drift far from the rate we gave rpois() (420). The summary below shows the mean and standard deviation for each promotion. It also shows the standard error of the mean (se). The standard error measures how much each average would move if we simulated another 28 days.

show/hide
hm_stats <- happy_meals |> 
  group_by(promotion) |> 
  summarise(
    mean = mean(sold), 
    sd = sd(sold), 
    se = sd(sold) / sqrt(n()))
hm_stats

DRAW IT

The graph below puts each promotion’s 28 days back behind its bar. The bar is the average, the points are the individual days, and the error bars stretch two standard errors above and below the average. geom_jitter() nudges the points sideways so they don’t pile up. The points spread out more for the busier promotions, but the error bars stay short because each average is built from 28 days.

show/hide
ggplot(data = hm_stats, aes(x = promotion, y = mean)) + 
  geom_col(aes(fill = promotion), show.legend = FALSE) + 
  geom_jitter(data = happy_meals, aes(y = sold), 
    width = 0.2, height = 0, alpha = 0.5, size = 1) + 
  geom_errorbar(aes(ymin = mean - 2 * se, ymax = mean + 2 * se), 
    width = 0.3, linewidth = 0.8) + 
  labs(x = "Toy promotion", y = "Happy Meals sold per day")

NAME IT

Each day’s sales come from a Poisson distribution with the promotion’s rate:

\[ X \sim \text{Poisson}(\lambda) \]

For a Poisson distribution, the variance equals \(\lambda\), so the standard deviation is \(\sqrt{\lambda}\). For Teenie Beanie Babies that’s \(\sqrt{420} \approx 20.5\) Happy Meals a day, and our simulated days have a standard deviation of 21.8. The average of \(n\) days has a much smaller spread, \(\sqrt{\lambda / n}\), which is the standard error:

\[ \bar{X} \approx \text{Normal}\left(\lambda, \; \sqrt{\lambda / n}\right) \]

With \(n = 28\) days, the Teenie Beanie Babies average should land within about \(2 \times \sqrt{420 / 28} \approx 7.7\) Happy Meals of 420. Ours is 417.6. That’s why the bars are trustworthy here: the gaps between promotions (about 50 or more Happy Meals a day) are much larger than the error bars. Try cutting the 28 in tidyr::uncount() down to 3 days and watch the error bars grow.

CHANGE IT

So far each bar shows what we expect: steady days of sales, with the average sitting in the middle of them. Now we’ll change the data. Suppose our restaurant runs out of Teenie Beanie Babies after 10 days. For the rest of the promotion, sales drop to about 120 Happy Meals a day. We expect a shorter Teenie Beanie Babies bar.

show/hide
set.seed(1997)
hm_sellout <- happy_meals |>
  mutate(sold = if_else(
    promotion == "Teenie Beanie Babies" & day > 10, # toys sold out
    rpois(n(), lambda = 120), sold))
hm_sellout_stats <- hm_sellout |>
  group_by(promotion) |>
  summarise(
    mean = mean(sold),
    sd = sd(sold),
    se = sd(sold) / sqrt(n()))
hm_sellout_stats

Below we redraw the graph from DRAW IT with the sellout data.

show/hide
ggplot(data = hm_sellout_stats, aes(x = promotion, y = mean)) +
  geom_col(aes(fill = promotion), show.legend = FALSE) +
  geom_jitter(data = hm_sellout, aes(y = sold),
    width = 0.2, height = 0, alpha = 0.5, size = 1) +
  geom_errorbar(aes(ymin = mean - 2 * se, ymax = mean + 2 * se),
    width = 0.3, linewidth = 0.8) +
  labs(x = "Toy promotion", y = "Happy Meals sold per day")

The Teenie Beanie Babies bar drops to 227 Happy Meals a day, nearly the same height as Hot Wheels (230). On their own, those two bars tell us the promotions sold about the same. The points tell a different story. Hot Wheels had 28 ordinary days, but Teenie Beanie Babies had 10 busy days near 420 and 18 slow days near 120. Its average describes none of them.

The error bar grows to about 57 Happy Meals above and below the mean. That warns us something is off, but it can’t show the two clumps. I’ve found this is the main risk with summary bar graphs. A bar only shows the average, so plot the raw data at least once before trusting it.

9.4 Grammar

CODE

  • Create labels with labs()

  • Initialize the graph with ggplot() and provide data

  • Map promotion to x and avg_sold to y

  • Inside the aes() of geom_col(), map promotion to fill

  • Outside the aes() of geom_col(), remove the legend with show.legend = FALSE

show/hide
labs_sum_col <- labs(
    title = "Happy Meals",
    caption = "Simulated data",
    subtitle = "Average Happy Meals sold per day\nduring each toy promotion",
    x = "Toy promotion",
    y = "Average sold per day")
ggp2_sum_col <- ggplot(data = hm_sum_col,
    aes(x = promotion,
        y = avg_sold)) +
    geom_col(aes(fill = promotion), 
        show.legend = FALSE)  
ggp2_sum_col + 
    labs_sum_col

GRAPH

9.5 More info

Below is more information on geom_bar() vs. geom_col().

9.5.1 Identity vs. Count

  • The geom_bar() geom will also create summary bar graphs, but we have to switch the stat argument to "identity".
show/hide
ggplot(data = hm_sum_col,
    aes(x = promotion,
        y = avg_sold)) +
    geom_bar(aes(fill = promotion),
        show.legend = FALSE,
        stat = "identity") +
    labs_sum_col

9.5.2 geom_bar() vs. geom_col()


  • geom_bar() will map a categorical variable to the x or y and display counts for the discrete levels (see stat_count() for more info)

  • geom_col() will map both x and y aesthetics, and is used when we want to display numerical (quantitative) values across the levels of a categorical variable. geom_col() assumes these values have been created in their own column (see stat_identity() for more info)