在ggplot中过滤多年的月份
Filter month for multiple years in ggplot
下面有 D
data.frame
,我想使用 ggplot
绘制。但是,我看到 data
对于 September
永远不会得到 plotted
。有没有更好的方法来完成 scale_x_continuous
中的 labels
或整个 Data.frame D
中的 ggplotting
?
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))
尝试指定 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))
我将进行如下修改,以利用 ggplot2 对日期的 built-in 支持。
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))
下面有 D
data.frame
,我想使用 ggplot
绘制。但是,我看到 data
对于 September
永远不会得到 plotted
。有没有更好的方法来完成 scale_x_continuous
中的 labels
或整个 Data.frame D
中的 ggplotting
?
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))
尝试指定 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))
我将进行如下修改,以利用 ggplot2 对日期的 built-in 支持。
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))