14.7 C
London
Tuesday, July 2, 2024
HomeTidyverse in Rggplot2 in RHow to Order the Bars in a ggplot2 Bar Chart

How to Order the Bars in a ggplot2 Bar Chart

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

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 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

Additional Resources

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

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories