There's no ggplot method for this that I know of, but you can generate the bars pretty easily and use geom_rect
.
library(ggplot2)
library(dplyr)
library(lubridate)
df <- data.frame(
date = seq.Date(from = as.Date("2015/01/01"), to = as.Date("2018/01/01"), by = 1),
data = runif(1097)
)
datebreaks <- seq(as.Date("2015/01/01"), as.Date("2018/01/01"), by = "3 month")
# Generate bars
df_bars <- data.frame(
xmin = seq(as.Date("2015/01/01"), as.Date("2017/07/01"), by = "6 months"),
ymin = -Inf, ymax = Inf
) %>%
mutate(xmax = xmin + months(3))
ggplot(df) +
geom_rect(data = df_bars, aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax),
fill = '#55555555') +
geom_line(aes(x = date, y = data)) +
scale_x_date(breaks = datebreaks, expand = c(0,0),
labels = function(x) paste0(year(x), ' Q', quarter(x))) +
ylim(c(-1,2))
EDIT: I added a line formatting the x-axis
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…