Home > OS >  Resorting axis ggplot2
Resorting axis ggplot2

Time:04-09

I would like to sort the x axis to read Jan - Dec. Here is my attempt:

temp = structure(list(Month_Year = c("2021-01", "2021-02", "2021-03", 
"2021-04", "2021-05", "2021-06", "2021-07", "2021-08", "2021-09", 
"2021-10", "2021-11", "2021-12", "2022-01"), Percent = c(75, 
100, 100, 98.6, 83.3, 83.3, 73.3, 83.3, 97.1, 93.1, 76.5, 100, 
100), Year = c(2021, 2021, 2021, 2021, 2021, 2021, 2021, 2021, 
2021, 2021, 2021, 2021, 2022), MonthN = c(1, 2, 3, 4, 5, 6, 7, 
8, 9, 10, 11, 12, 1), Month = c("Jan", "Feb", "Mar", "Apr", "May", 
"Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "Jan")), class = "data.frame", row.names = 60:72)

ggplot(temp, aes(x = Month, y = Percent, group=Year, colour=factor(Year)))  
  geom_line()  
  geom_point()  
  labs(x="Month", colour="Year")  
  theme_classic()

CodePudding user response:

Convert your month column to a factor with levels set in the right order. In your case this could be pretty easily achieved with the month.abb constant.

library(ggplot2)

ggplot(temp, aes(x = factor(Month, levels = month.abb), y = Percent, group = Year, colour = factor(Year)))  
  geom_line()  
  geom_point()  
  labs(x = "Month", colour = "Year")  
  theme_classic()

  • A second option would to reorder your Monnth column by your MonthN column, i.e. or reorder(Month, MonthN).

CodePudding user response:

One option is to convert your Month_Year column from a character into a true Date format. This would make it easy to extract things like the year, month, and abbreviation for the month automatically using the {lubridate} package, which may be helpful if you have to annotate a large dataset in this way. Then you can use forcats::fct_reorder() to put the abbreviations in the correct order.

library(tidyverse)
library(lubridate)

d <- structure(list(Month_Year = c("2021-01", "2021-02", "2021-03", "2021-04", "2021-05", "2021-06", "2021-07", "2021-08", "2021-09", "2021-10", "2021-11", "2021-12", "2022-01"), Percent = c(75, 100, 100, 98.6, 83.3, 83.3, 73.3, 83.3, 97.1, 93.1, 76.5, 100, 100)), class = "data.frame", row.names = 60:72)

# extract month and year info directly from date
d %>% 
  mutate(date = ym(Month_Year),
         year = year(date),
         month = month(date),
         month_abr = fct_reorder(month.abb[month], month)) %>% 
  ggplot(aes(x = month_abr, y = Percent, group = year, colour = factor(year)))  
  geom_line()  
  geom_point()  
  labs(x = "Month", colour = "Year")  
  theme_classic()

Created on 2022-04-08 by the reprex package (v2.0.1)

  • Related