3.8 Making a Proportional Stacked Bar Graph

3.8.1 Problem

You want to make a stacked bar graph that shows proportions (also called a 100% stacked bar graph).

3.8.3 Discussion

With position = "fill", the y values will be scaled to go from 0 to 1. To print the labels as percentages, use scale_y_continuous(labels = scales::percent).


Using scales::percent is a way of using the percent function from the scales package. You could instead do library(scales) and then just use scale_y_continuous(labels = percent). This would also make all of the functions from scales available in the current R session.

To make the output look a little nicer, you can change the color palette and add an outline. This is shown in (Figure 3.21):

Proportional stacked bar graph with reversed legend, new palette, and black outline

Figure 3.21: Proportional stacked bar graph with reversed legend, new palette, and black outline

Instead of having ggplot2 compute the proportions automatically, you may want to compute the proportional values yourself. This can be useful if you want to use those values in other computations.

To do this, first scale the data to 100% within each stack. This can be done by using group_by() together with mutate() from the dplyr package.

To calculate the percentages within each Weight group, we used dplyr’s group_by() and mutate() functions. In the example here, the group_by() function tells dplyr that future operations should operate on the data frame as though it were split up into groups, on the Date column. The mutate() function tells it to calculate a new column, dividing each row’s Weight value by the sum of the Weight column within each group.


You may have noticed that cabbage_exp and ce print out differently. This is because cabbage_exp is a regular data frame, while ce is a tibble, which is a data frame with some extra properties. The dplyr package creates tibbles. For more information, see Chapter 15.

After computing the new column, making the graph is the same as with a regular stacked bar graph.

3.8.4 See Also

For more on transforming data by groups, see Recipe 15.16.