Home > database >  How to stop R from alphabetizing?
How to stop R from alphabetizing?

Time:01-18

I am trying to do a monthly bar chart but it keeps putting april as the first month instead of january. Is there any way I can fix this so it is in the correct order?

Number <- c(41,23,22,16,21,10,10,13,20,12,15,16,18,20,18,92,81,72,73,47,57,12,23,12,12,23,34,54,32,5,65,44,55,66,55,44)
 
Year <- c("2018","2018","2018","2018","2018","2018","2018","2018","2018","2018","2018","2018","2019","2019","2019","2019","2019","2019","2019","2019","2019","2019","2019","2019","2020","2020","2020","2020","2020","2020","2020","2020","2020","2020","2020","2020")
 
Month <- c("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")
 
library(ggplot2)
adultmonthly <- data.frame(Number,Year,Month)

ggplot(adultmonthly, aes(Year, Number, fill = Month))  
  geom_bar(colour = "black", stat="identity", position = "dodge")  
  labs(title="Frequency of children affected")

My bar plot

CodePudding user response:

You have to convert your Month variable to factor with the desired order, which in your case is pretty easy using the base constant month.abb:

library(ggplot2)

adultmonthly <- data.frame(Number, Year, Month)

adultmonthly$Month <- factor(adultmonthly$Month, levels = month.abb)

ggplot(adultmonthly, aes(Year, Number, fill = Month))  
  geom_bar(colour = "black", stat = "identity", position = "dodge")  
  labs(title = "Frequency of children affected")

enter image description here

  • Related