How to Order the Bars in a ggplot2 Bar Chart?

In a ggplot2 bar chart, the bars should be ordered according to the order of the variables specified in the aes() function. For grouped bar charts, the order should be specified in the fill argument of the aes() function. If the order needs to be reversed, the scale_x_reverse() function can be used to reverse the order of the bars. Additionally, the arrange() function from the dplyr package can be used to further customize the order of the bars.


By default, ggplot2 orders the bars in a bar chart using the following orders:

  • Factor variables are ordered by factor levels.
  • Character variables are order in alphabetical order.

However, often you may be interested in ordering the bars in some other specific order.

This tutorial explains how to do so using the following data frame:

#create data frame
df <- data.frame(team = c('B', 'B', 'B', 'A', 'A', 'C'),
                 points = c(12, 28, 19, 22, 32, 45),
                 rebounds = c(5, 7, 7, 12, 11, 4))

#view structure of data frame
str(df)

'data.frame':	6 obs. of  3 variables:
 $ team    : Factor w/ 3 levels "A","B","C": 2 2 2 1 1 3
 $ points  : num  12 28 19 22 32 45
 $ rebounds: num  5 7 7 12 11 4

Example 1: Order the Bars Based on a Specific Factor Order

If we attempt to create a bar chart to display the frequency by team, the bars will automatically appear in alphabetical order:

library(ggplot2)

ggplot(df, aes(x=team)) +
  geom_bar()

The following code shows how to order the bars by a specific order:

#specify factor level order
df$team = factor(df$team, levels = c('C', 'A', 'B'))

#create bar chart again 
ggplot(df, aes(x=team)) +
  geom_bar()

Example 2: Order the Bars Based on Numerical Value

We can also order the bars based on numerical values. For example, the following code shows how to order the bars from largest to smallest frequency using the reorder() function:

library(ggplot2)

ggplot(df, aes(x=reorder(team, team, function(x)-length(x)))) +
  geom_bar()

Order bars in ggplot2 bar chart

We can also order the bars from smallest to largest frequency by taking out the minus sign in the function() call within reorder() function:

library(ggplot2)

ggplot(df, aes(x=reorder(team, team, function(x) length(x)))) +
  geom_bar()

Order bars smallest to largest in ggplot2 bar chart

Documentation for the geom_bar() function.
Documentation for the reorder() function.
A complete list of R tutorials on arabpsychology.

x