Search code examples
rdataframeggplot2axisaxis-labels

Filter month for multiple years in ggplot


I have the D data.frame below that I would like to plot using ggplot. However, I see that data for September never get plotted. Is there a better way to do the labels in scale_x_continuous or the ggplotting of entire Data.frame D?

library(lubridate)
library(tidyverse)

D <- data.frame(Date = seq(as.Date("2001-01-01"), to= as.Date("2002-12-31"), by="day"),
                A = runif(730, 1,70)) %>% 
    mutate(Year = year(Date), Month = month(Date), Day = day(Date), JDay = yday(Date)) %>% 
    dplyr::filter(between(Month, 5, 9)) %>% 
    group_by(Year) %>% 
    mutate(CumA  = cumsum(A)) %>% 
  select(c(3,6,7))

ggplot(D, aes(x = JDay, y = CumA, col = as.factor(Year)))+
  geom_line()+
  scale_x_continuous(limits = c(121,273), labels = c("May", "Jun","Jul","Aug","Sep"), 
                     expand = c(0,0))

Solution

  • I would revise as follows, to make use of the built-in support for dates by ggplot2.

    D <- data.frame(Date = seq(as.Date("2001-01-01"), to= as.Date("2002-12-31"), by="day"),
                    A = runif(730, 1,70)) %>% 
      mutate(Year = year(Date), Month = month(Date), Day = day(Date), JDay = yday(Date)) %>% 
      dplyr::filter(between(Month, 5, 9)) %>% 
      group_by(Year) %>% 
      mutate(
        CumA  = cumsum(A),
        plot_Date = Date
      )
    year(D$plot_Date) <- 2001
    
    ggplot(D, aes(x = plot_Date, y = CumA, col = as.factor(Year)))+
      geom_line()+
      scale_x_date(date_breaks = '1 month', date_labels = '%B', expand = c(0, 0))
    

    enter image description here