
8 Grouped bar graphs
theme_jurassic()
Graphs in this chapter use ggrewindr::theme_jurassic(), modeled on the Jurassic Park (1993) Post Office souvenir stamp sheet: a black sheet with a logo red frame, a dark jungle plot area, stamp yellow titles, red, yellow, sunset orange, cream, and tan marks, and a Macondo title.
8.1 Description
Grouped bar graphs compare multiple values across categories. Each category has a cluster of bars. X-axis labels show categories and y-axis values. Colors or patterns differentiate subsets, and a legend is shown on the side or top of the graph.
geom_col() displays ‘grouped’ numbers across the levels (or groups) of a categorical variable.
8.2 Set up
PACKAGES
Install packages.
show/hide
library(ggplot2)
library(dplyr) # for tibble() and data manipulation
library(tidyr) # for uncount()DATA
In Jurassic Park (1993), every species lives in its own paddock. We’ll simulate the weight of every dinosaur on two islands: Isla Nublar (the park) and Isla Sorna (Site B from The Lost World (1997)). Both islands have the same five species, and each species gets a head count on each island (n) and its own normal distribution of weights (mean_tons and sd_tons).
tidyr::uncount() repeats each row n times (one row per dinosaur), and rnorm() draws each dinosaur’s weight. Then we add up the weights in each paddock on each island (total_tons). Setting the seed with set.seed() means you’ll get the same dinosaurs every time you run the code below.
show/hide
set.seed(1993) # same dinosaur weights every time the code runs
jp_dinos <- tibble(
island = rep(c("Isla Nublar", "Isla Sorna"), each = 5), # the park and the second island
species = rep(c("Brachiosaurus", "Triceratops", "Tyrannosaurus", # five species on each island
"Gallimimus", "Velociraptor"), times = 2),
n = c(3, 5, 2, 20, 8, # number of animals of each species on Isla Nublar
2, 7, 3, 14, 12), # number of animals of each species on Isla Sorna
mean_tons = rep(c(40, 9, 8, 0.45, 0.15), times = 2), # average weight (tons), same on both islands
sd_tons = rep(c(5, 1.2, 1, 0.08, 0.03), times = 2) # spread of each species' weights
) |>
tidyr::uncount(n) |> # one row per animal
mutate(
weight_tons = round(rnorm(n(), mean = mean_tons, sd = sd_tons), 2) # each animal's weight
) |>
select(island, species, weight_tons)
jp_paddocks <- jp_dinos |>
group_by(island, species) |> # one group per paddock on each island
summarise(total_tons = sum(weight_tons), .groups = "drop") # total weight in each paddock
glimpse(jp_paddocks)
#> Rows: 10
#> Columns: 3
#> $ island <chr> "Isla Nublar", "Isla Nublar",…
#> $ species <chr> "Brachiosaurus", "Gallimimus"…
#> $ total_tons <dbl> 115.83, 8.88, 43.08, 15.27, 1…8.3 Distribution
A grouped bar graph shows one number per group, and here that number is a total. Totals depend on two things: how many dinosaurs live in a paddock and how much each one weighs. Twenty Gallimimus still weigh less than two Tyrannosaurs. Below we’ll move from the dinosaurs, to a picture, to the formula.
COUNT IT
Start with the first six dinosaurs.
show/hide
head(jp_dinos, 6)Each Brachiosaurus weighs close to 40 tons, and each Triceratops weighs close to 9. For every paddock, the total is the number of dinosaurs times their average weight.
show/hide
jp_dinos |>
group_by(island, species) |>
summarise(
dinosaurs = n(),
mean_tons = mean(weight_tons),
total_tons = sum(weight_tons))
#> `summarise()` has regrouped the output.
#> ℹ Summaries were computed grouped by island and
#> species.
#> ℹ Output is grouped by island.
#> ℹ Use `summarise(.groups = "drop_last")` to
#> silence this message.
#> ℹ Use `summarise(.by = c(island, species))` for
#> per-operation grouping (`?dplyr::dplyr_by`)
#> instead.DRAW IT
Each bar in a grouped bar graph is a bar model: a total made of parts. Below we draw every dinosaur on Isla Nublar as its own segment and stack the segments in each paddock. The height of each stack is the paddock’s total, and the number of segments is its head count. The Gallimimus bar has 20 thin segments, and the Brachiosaurus bar has three thick ones.
show/hide
jp_dinos |>
filter(island == "Isla Nublar") |>
ggplot(aes(x = species, y = weight_tons, fill = species)) +
geom_col(color = "#111111", linewidth = 0.3, show.legend = FALSE) +
scale_x_discrete(guide = guide_axis(n.dodge = 2)) +
labs(x = "Paddock", y = "Total weight (tons)")
NAME IT
Each dinosaur’s weight comes from a normal distribution for its species, \(X_i \sim \text{Normal}(\mu, \sigma)\). A paddock’s total adds up \(n\) of these weights:
\[ T = X_1 + X_2 + \dots + X_n \sim \text{Normal}(n\mu, \; \sqrt{n}\,\sigma) \]
The expected total is \(n\mu\): \(3 \times 40 = 120\) tons for the Brachiosaurus paddock and \(20 \times 0.45 = 9\) tons for Gallimimus. The spread grows with \(\sqrt{n}\), not \(n\), because heavy and light dinosaurs partly cancel each other out. Our Brachiosaurus paddock on Isla Nublar weighs 115.8 tons, within one standard deviation (\(\sqrt{3} \times 5 \approx 8.7\) tons) of its expected 120.
CHANGE IT
So far the graph shows what we expect: the heavy species have the tallest bars on both islands. Now we’ll change the head counts of each dinosaur. Isla Sorna has no fences, and in the 1997 sequel its dinosaurs have been breeding on their own for years.
Suppose the Gallimimus herd there grew from 14 to 300. We still expect each Gallimimus to weigh under half a ton, so the herd’s bar should grow, but how much?
show/hide
set.seed(1993) # same seed as above
jp_herd <- jp_dinos |>
bind_rows(tibble(
island = "Isla Sorna",
species = "Gallimimus",
weight_tons = round(rnorm(286, mean = 0.45, sd = 0.08), 2))) # 286 more Gallimimus
jp_paddocks_herd <- jp_herd |>
group_by(island, species) |>
summarise(dinosaurs = n(), total_tons = sum(weight_tons), .groups = "drop")
jp_paddocks_herdBelow we redraw the same grouped bar graph with the new totals.
show/hide
ggplot(data = jp_paddocks_herd,
aes(x = species, y = total_tons)) +
geom_col(aes(fill = island), position = "dodge") +
scale_x_discrete(guide = guide_axis(n.dodge = 2)) +
labs(x = "Paddock", y = "Total weight (tons)", fill = "Island")
The lightest species now has the tallest bar in the graph. The Isla Sorna Gallimimus weigh 133.8 tons together, more than the 115.8 tons of Brachiosaurus on Isla Nublar. Nothing about a single Gallimimus changed; only the head count did. The bar can’t tell us whether its height comes from a few heavy animals or hundreds of light ones. I’ve found it’s worth checking the counts (like the dinosaurs column above) before reading a tall bar of totals as a sign of big animals.
8.4 Grammar
CODE
Grouped bar graphs expect the bar heights to already sit in a variable. We map that variable to the x or y aesthetic.
Create labels with
labs()Initialize the graph with
ggplot()and providedataMap
speciesto thexandtotal_tonsto theyMap
islandtofillinside theaes()ofgeom_col()Place each island’s bars side by side with
position = "dodge"Stagger the long paddock names over two lines with
scale_x_discrete(guide = guide_axis(n.dodge = 2))
show/hide
labs_grp_col <- labs(
title = "Jurassic Park",
caption = "Simulated data",
subtitle = "Total weight of the dinosaurs in each paddock, by island",
x = "Paddock",
y = "Total weight (tons)",
fill = "Island")
ggp2_grp_col <- ggplot(data = jp_paddocks,
aes(x = species,
y = total_tons)) +
geom_col(aes(fill = island),
position = "dodge") +
scale_x_discrete(guide = guide_axis(n.dodge = 2))
ggp2_grp_col +
labs_grp_colGRAPH

8.5 More info
We didn’t have to calculate total_tons (displayed on the y axis) by species because ggplot2 does this for us!
If we pass a categorical variable to the x (like species) and a continuous variable to y (like weight_tons), stat_summary() with fun = "sum" adds up y for each level of x and each island. geom_col() can’t do this with position = "dodge", because it draws each dinosaur’s bar on top of the others instead of adding them up:
show/hide
jp_dinos |>
ggplot(aes(x = species, y = weight_tons)) +
stat_summary(aes(fill = island),
fun = "sum", geom = "col",
position = "dodge") +
scale_x_discrete(guide = guide_axis(n.dodge = 2)) +
labs_grp_col
We can see the underlying totals using dplyr’s group_by() and summarise() functions.
show/hide
jp_dinos |>
dplyr::group_by(island, species) |>
dplyr::summarise(
`Total weight (tons)` = sum(weight_tons)
) |>
dplyr::ungroup() |>
dplyr::select(Island = island,
`Paddock` = species,
`Total weight (tons)`)| Island | Paddock | Total weight (tons) |
|---|---|---|
| Isla Nublar | Brachiosaurus | 115.83 |
| Isla Nublar | Gallimimus | 8.88 |
| Isla Nublar | Triceratops | 43.08 |
| Isla Nublar | Tyrannosaurus | 15.27 |
| Isla Nublar | Velociraptor | 1.33 |
| Isla Sorna | Brachiosaurus | 84.18 |
| Isla Sorna | Gallimimus | 6.16 |
| Isla Sorna | Triceratops | 63.48 |
| Isla Sorna | Tyrannosaurus | 22.84 |
| Isla Sorna | Velociraptor | 1.76 |