在ggplot中过滤多年的月份

时间:2020-09-03 15:35:55

标签: r dataframe ggplot2 axis axis-labels

我下面有D data.frame,我想使用ggplot进行绘制。但是,我看到data的{​​{1}}永远不会得到September。是否有更好的方法来处理plotted中的labels或整个scale_x_continuous中的ggplotting

Data.frame D

2 个答案:

答案 0 :(得分:1)

尝试通过指定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

答案 1 :(得分:1)

我将作如下修改,以利用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