Stacked Bar Plot

Overview #

A stacked bar plot is used to compare groups of observations and also show the proportions of the observations within each group.

The overall height of the bars is the sum of the different observations within the groups.

A stacked bar plot is analogous to a stacked area plot.

When to use #

A stacked bar plot works well to convey the total sum of a given group.

This sort of visualization makes it straightforward to compare groups against one another.

It’s not so great for drawing comparisons between observations within groups. For something like that, you’re better off using a grouped bar plot.

Data #

To assemble a stacked bar plot, the data must include:

  • A numerical measure
  • A categorical value that identifies the observation
  • A categorical value that identifies the group

Here’s an example of what that data might look like:

measure observation group
10 A Group 1
15 B Group 1
7 A Group 2
12 B Group 2

The observation value is used to partition the bars, while the group value is used to identify each bar.

R #

A grouped bar plot can be put together in R using the ggplot2 package.

Let’s recreate the example data from above.

example <- tribble(
  ~measure, ~observation, ~group,
  10, "A", "Group 1",
  15, "B", "Group 1",
  7, "A", "Group 2",
  12, "B", "Group 2"
)

example
## # A tibble: 4 × 3
##   measure observation group  
##     <dbl> <chr>       <chr>  
## 1      10 A           Group 1
## 2      15 B           Group 1
## 3       7 A           Group 2
## 4      12 B           Group 2

Now let’s pass that to ggplot2.

example %>%
  ggplot() +
  geom_bar(stat = "identity", position = "stack", aes(x = group, y = measure, fill = observation))

The position = "stack" is what distinguishes a stacked bar plot from other types of bar plots.

Note that in this particular plot, the height of the bars is mapped to the measure with y = measure.

The distinct groups are mapped to the different groupings with x = group.

The different observations with the groups are identified with a fill color, fill = observation.