Charlotte
Charlotte

Reputation: 11

ggplot2: how to fix the order of the x axis of a geom_bar

I'm new to R. I've produced a bar chart using ggplot2; however, when it plots, the order of the months change along the x axis. I am not sure how to write the code to prevent this from happening and to get the months in the correct order along the x axis.

df <-
  data.frame(
    month = c(
      "May",
      "June",
      "July",
      "August",
      "September",
      "October",
      "November"
    ),
    cpue = c(2.40, 4.20, 6.16, 5.25, 3.32, 2.33, 0.91)
  )

ggplot(data = df, aes(x = month, y = cpue)) +
  geom_bar(stat = "identity", width =
             0.5, fill = "black") + labs(x = "Month", y = "CPUE") + theme(
               axis.text = element_text(size = 12),
               axis.title = element_text(size = 14),
               axis.line = element_line(colour = "black"),
               panel.grid.major = element_blank()
             )

Upvotes: 1

Views: 2216

Answers (3)

Gui Albernaz
Gui Albernaz

Reputation: 45

You can also try to use reorder within the ggplot. It allows you to reorder one variable based on another variable, like this:

library(tidyverse)
ggplot(data = df, aes(x = reorder(month, cpue), y = cpue))

Or if you want it in descending order, just add a minus, like this:

ggplot(data = df, aes(x = reorder(month, -cpue), y = cpue))

Upvotes: 0

AndrewGB
AndrewGB

Reputation: 16876

Another option is to use fct_inorder from forcats (part of tidyverse) to keep the original order of the data.

library(tidyverse)

ggplot(data = df, aes(x = fct_inorder(month), y = cpue)) +
  geom_bar(stat = "identity", width =
             0.5, fill = "black") + labs(x = "Month", y = "CPUE") + theme(
               axis.text = element_text(size = 12),
               axis.title = element_text(size = 14),
               axis.line = element_line(colour = "black"),
               panel.grid.major = element_blank()
             )

Output

enter image description here

Upvotes: 0

Aliyan Haq
Aliyan Haq

Reputation: 312

It is not randomly changing the x axis, but instead it is trying to put the x-axis in an alphabetical order.

An easy fix to this is to make your df ordered using levels.

df <- data.frame(month=c("May","June","July","August","September","October","November"),cpue=c(2.40,4.20,6.16,5.25,3.32,2.33,0.91))

Now that your df is made, we can easily level the column, we will use for the x-axis, in this case the month column:

df$month <- factor(df$month, levels = df$month)

Now, when we plot the bar graph, it is in the order we provided it with from the data frame.

  ggplot(data=df,aes(x=month,y=cpue)) + 
  geom_bar(stat="identity",width=0.5,fill="black") + 
  labs(x="Month",y="CPUE") + 
  theme(axis.text=element_text(size=12),axis.title=element_text(size=14),axis.line=element_line(colour="black"),panel.grid.major = element_blank())

Hopefully this helps!

Upvotes: 2

Related Questions