How to reorder bars in a stacked bar chart in ggplot2?

In ggplot2, you can reorder the bars in a stacked bar chart by changing the order of the factor levels in the data set used to create the chart. You can use the reorder() function to do this. For example, to reorder the bars in a stacked bar chart by the sum of the values, you can use the sum of the values as the new order of the factor levels.


You can use the following basic syntax to reorder the position of bars in a stacked bar chart in ggplot2:

#specify order of bars (from top to bottom)
df$fill_var <- factor(df$fill_var, levels=c('value1', 'value2', 'value3', ...))

#create stacked bar chart
ggplot(df, aes(x=x_var, y=y_var, fill=fill_var)) + 
    geom_bar(position='stack', stat='identity')

The following example shows how to use this syntax in practice.

Example: Reorder Bars in Stacked Bar Chart in ggplot2

Suppose we have the following data frame in R that shows the points scored by various basketball players:

#create data frame
df <- data.frame(team=c('A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C'),
                 position=c('G', 'F', 'C', 'G', 'F', 'C', 'G', 'F', 'C'),
                 points=c(22, 12, 10, 30, 12, 17, 28, 23, 20))

#view data frame
df

  team position points
1    A        G     22
2    A        F     12
3    A        C     10
4    B        G     30
5    B        F     12
6    B        C     17
7    C        G     28
8    C        F     23
9    C        C     20

If we create a stacked bar chart to visualize the points scored by players on each team, ggplot2 will automatically stack the bars in alphabetical order:

library(ggplot2)

#create stacked bar chart
ggplot(df, aes(x=team, y=points, fill=position)) + 
    geom_bar(position='stack', stat='identity')

Notice that each stacked bar displays the position (from top to bottom) in alphabetical order.

To reorder the bars in a specific way, we can convert the position variable to a factor and use the levels argument to specify the order that the bars should be in (from top to bottom) in the stacked bar chart:

library(ggplot2)

#convert 'position' to factor and specify level order
df$position <- factor(df$position, levels=c('F', 'G', 'C'))

#create stacked bar chart
ggplot(df, aes(x=team, y=points, fill=position)) + 
    geom_bar(position='stack', stat='identity')

The bars are now stacked (from top to bottom) in the exact order that we specified within the levels argument.

The following tutorials explain how to perform other common tasks in ggplot2:

x