16  Stacked bar charts

One of the elements of data visualization excellence is inviting comparison. Often that comes in showing what proportion a thing is in relation to the whole thing. With bar charts, we’re showing magnitude of the whole thing. If we have information about the parts of the whole, we can stack them on top of each other to compare them, showing both the whole and the components. And it’s a simple change to what we’ve already done.

We’re going to use a dataset of college basketball games from this past season.

For this walkthrough:

Load the tidyverse.

library(tidyverse)

And the data.

games <- read_csv("data/logs24.csv")
Rows: 11990 Columns: 48
── Column specification ────────────────────────────────────────────────────────
Delimiter: ","
chr   (8): Season, TeamFullName, Opponent, HomeAway, W_L, URL, Conference, Team
dbl  (39): Game, TeamScore, OpponentScore, TeamFG, TeamFGA, TeamFGPCT, Team3...
date  (1): Date

ℹ Use `spec()` to retrieve the full column specification for this data.
ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.

What we have here is every game in college basketball this past season. The question we want to answer is this: Who were the best rebounders in the Big Ten? And what role did offensive and defensive rebounds play in making that happen?

So to make this chart, we have to just add one thing to a bar chart like we did in the previous chapter. However, it’s not that simple.

We have game data, and we need season data. To get that, we need to do some group by and sum work. And since we’re only interested in the Big Ten, we have some filtering to do too. For this, we’re going to measure offensive rebounds and total rebounds, and then we can calculate defensive rebounds. So if we have all the games a team played, and the offensive rebounds and total rebounds for each of those games, what we need to do to get the season totals is just add them up.

games |> 
  filter(!is.na(TeamTotalRebounds)) |> 
  group_by(Conference, Team) |> 
  summarise(
    SeasonOffRebounds = sum(TeamOffRebounds),
    SeasonTotalRebounds = sum(TeamTotalRebounds)
  ) |>
  mutate(
    SeasonDefRebounds = SeasonTotalRebounds - SeasonOffRebounds
  ) |> 
  select(
    -SeasonTotalRebounds
  ) |> 
  filter(Conference == "Big Ten MBB")
# A tibble: 14 × 4
# Groups:   Conference [1]
   Conference  Team           SeasonOffRebounds SeasonDefRebounds
   <chr>       <chr>                      <dbl>             <dbl>
 1 Big Ten MBB Illinois                     423              1000
 2 Big Ten MBB Indiana                      254               803
 3 Big Ten MBB Iowa                         279               823
 4 Big Ten MBB Maryland                     332               734
 5 Big Ten MBB Michigan                     286               720
 6 Big Ten MBB Michigan State               305               807
 7 Big Ten MBB Minnesota                    272               785
 8 Big Ten MBB Nebraska                     277               899
 9 Big Ten MBB Northwestern                 248               742
10 Big Ten MBB Ohio State                   338               889
11 Big Ten MBB Penn State                   264               704
12 Big Ten MBB Purdue                       425              1044
13 Big Ten MBB Rutgers                      332               736
14 Big Ten MBB Wisconsin                    309               797

By looking at this, we can see we got what we needed. We have 14 teams and numbers that look like season totals for two types of rebounds. Save that to a new dataframe.

games |> 
  filter(!is.na(TeamTotalRebounds)) |> 
  group_by(Conference, Team) |> 
  summarise(
    SeasonOffRebounds = sum(TeamOffRebounds),
    SeasonTotalRebounds = sum(TeamTotalRebounds)
  ) |>
  mutate(
    SeasonDefRebounds = SeasonTotalRebounds - SeasonOffRebounds
  ) |> 
  select(
    -SeasonTotalRebounds
  ) |> 
  filter(Conference == "Big Ten MBB") -> rebounds

Now, the problem we have is that ggplot wants long data and this data is wide. So we need to use tidyr to make it long, just like we did in the transforming data chapter.

rebounds |> 
  pivot_longer(
    cols=starts_with("Season"), 
    names_to="Type", 
    values_to="Rebounds")
# A tibble: 28 × 4
# Groups:   Conference [1]
   Conference  Team     Type              Rebounds
   <chr>       <chr>    <chr>                <dbl>
 1 Big Ten MBB Illinois SeasonOffRebounds      423
 2 Big Ten MBB Illinois SeasonDefRebounds     1000
 3 Big Ten MBB Indiana  SeasonOffRebounds      254
 4 Big Ten MBB Indiana  SeasonDefRebounds      803
 5 Big Ten MBB Iowa     SeasonOffRebounds      279
 6 Big Ten MBB Iowa     SeasonDefRebounds      823
 7 Big Ten MBB Maryland SeasonOffRebounds      332
 8 Big Ten MBB Maryland SeasonDefRebounds      734
 9 Big Ten MBB Michigan SeasonOffRebounds      286
10 Big Ten MBB Michigan SeasonDefRebounds      720
# … with 18 more rows

What you can see now is that we have two rows for each team: one for offensive rebounds, one for defensive rebounds. This is what ggplot needs. Save it to a new dataframe.

rebounds |> 
  pivot_longer(
    cols=starts_with("Season"), 
    names_to="Type", 
    values_to="Rebounds") -> reboundswide

Building on what we learned in the last chapter, we know we can turn this into a bar chart with an x value, a weight and a geom_bar. What we are going to add is a fill. The fill will stack bars on each other based on which element it is. In this case, we can fill the bar by Type, which means it will stack the number of offensive rebounds on top of defensive rebounds and we can see how they compare.

ggplot() + 
  geom_bar(
    data=reboundswide, 
    aes(x=Team, weight=Rebounds, fill=Type)) + 
  coord_flip()

What’s the problem with this chart?

There’s a couple of things, one of which we’ll deal with now: The ordering is alphabetical (from the bottom up). So let’s reorder the teams by Rebounds.

ggplot() + 
  geom_bar(
    data=reboundswide, 
    aes(x=reorder(Team, Rebounds), 
        weight=Rebounds, 
        fill=Type)) + 
  coord_flip()

And just like that … Purdue, the team with the best record in the league, comes out on top. Maryland is ninth, which seems a little worse than its record would indicate.