Search code examples
rggplot2filtertidyverseaxis-labels

seasonal ggplot in R?


I am looking at data from Nov to April and would like to have a plot starting from Nov to April. Below is my sample code to screen out month of interests.

library(tidyverse)
mydata = data.frame(seq(as.Date("2010-01-01"), to=as.Date("2011-12-31"),by="days"), A = runif(730,10,50))
colnames(mydata) = c("Date", "A")
DF = mydata %>%
     mutate(Year = year(Date), Month = month(Date), Day = day(Date)) %>%
     filter(Month == 11 | Month == 12 | Month == 01 | Month == 02 | Month == 03 | Month == 04)

I tried to re-order the data starting at month 11 followed by month 12 and then month 01,02,03,and,04. I used the code factor(Month, levels = c(11,12,01,02,03,04)) along with the code above but it didn't work. I wanted a plot that starts at month Nov and ends on April. The following code gave me attached plot

ggplot(data = DF, aes(Month,A))+
  geom_bar(stat = "identity")+ facet_wrap(~Year, ncol = 2)

enter image description here

Right now, the plot is starting at January all the way to December- I dont want this. I want the plot starting at November, and all the way to April. I tried to label the plot using scale_x_date(labels = date_format("%b", date_breaks = "month", name = "Month") which didn't work. Any help would


Solution

  • I converted Month to character before applying factor() and it worked.

    DF = mydata %>%
      mutate(Year = year(Date), Month = month(Date), Day = day(Date)) %>%
      filter(Month %in% c(11, 12, 1, 2, 3, 4)) %>%
      mutate(Month = sprintf("%02d", Month)) %>%
      mutate(Month = factor(Month, levels = c("11","12","01","02","03","04")))
    
    ggplot(data = DF, aes(Month,A))+
      geom_bar(stat = "identity")+ facet_wrap(~Year, ncol = 2)
    

    Output:

    enter image description here