Hydro
Hydro

Reputation: 1117

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))

Upvotes: 0

Views: 374

Answers (2)

Edo
Edo

Reputation: 7858

Try by specifying breaks:

dates <- seq(as.Date("2001-05-01"), as.Date("2001-09-01"), by = "month")

ggplot(D, aes(x = JDay, y = CumA, col = as.factor(Year)))+
 geom_line()+
 scale_x_continuous(breaks = yday(dates),
                    labels = month(dates, label = TRUE), 
                    expand = c(0,0))

enter image description here

Upvotes: 1

Axeman
Axeman

Reputation: 35382

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

Upvotes: 1

Related Questions