Lubridate is nice for some things, but I much prefer zoo::as.yearmon
for months and years. There is even a nice scale_x_yearmon
function for ggplot
:
library(zoo)
df %>%
mutate (Month = zoo::as.yearmon(Date)) %>%
group_by(Month, Var1) %>%
summarize (sum = sum(numeric_variable)) %>%
ggplot(aes(Month, sum)) +
geom_col() +
facet_wrap(. ~ Var1, scales ="free_y") +
zoo::scale_x_yearmon(format = "%b")
Sample data:
set.seed(123)
df <- data.frame(Date = rep(seq(as.Date("2019-01-01"),as.Date("2020-12-31"), by = "day"),2),
Var1 = rep(LETTERS[1:2],each = 731),
numeric_variable = round(runif(2*731,1,100)))
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…