由于缺乏样本数据,我创建了一些。
library(ggplot2)
library(dplyr)
daytime <- rep(rep(c("day", "night"), each = 12),10)
df <- data.frame(date = 1:length(daytime), daytime, value = rnorm(length(daytime)))
> head(df)
date daytime value
1 1 day -0.7016900
2 2 day -0.5886091
3 3 day -0.1962264
4 4 day 1.3621115
5 5 day -1.5810459
6 6 day -0.6598885
然后我确定了每天和每个晚上的开始和结束。对于样本数据来说,这不是必需的,但我想真实的数据并不那么简单。
period <- case_when(daytime != lead(daytime) & daytime == "day" ~ "endDay",
daytime != lead(daytime) & daytime == "night" ~ "endNight",
daytime != lag(daytime) & daytime == "day" ~ "beginDay",
daytime != lag(daytime) & daytime == "night" ~ "beginNight")
period[1] <- "beginDay"
period[length(period)] <- "endNight"
结合两者:
rect <- cbind(df,period)
names(rect)[1] <- "date"
并创建 2 个数据帧,一个用于夜间,一个用于白天,以及每个时期对应的 x 值。
rect_night <- na.omit(rect[rect$daytime == "night", ])[ ,-2:-3]
rect_night <- data.frame(start = rect_night[rect_night$period == "beginNight", 1],
end = rect_night[rect_night$period == "endNight", 1])
rect_day <- na.omit(rect[rect$daytime == "day", ])
rect_day <- data.frame(start = rect_day[rect_day$period == "beginDay", 1],
end = rect_day[rect_day$period == "endDay", 1])
将所有内容放在一个情节中。
ggplot(alpha = 0.3) +
geom_rect(data = rect_night,aes(xmin = start, xmax = end, ymin = -5, ymax = 5), fill = "grey") +
geom_rect(data = rect_day,aes(xmin = start, xmax = end, ymin = -5, ymax = 5), fill = "yellow") +
geom_line(data = df, aes(x = date, y = value))