[英]How to plot a fringe in zoo object time series to highlight a period?
[英]Mark a period of time in a time-series-plot
首先,讓我們創建一些假數據:
d <- c("2019-01-01", "2019-01-02", "2019-01-03", "2019-01-04", "2019-01-03", "2019-04-06", "2019-04-03", "2019-05-07", "2019-05-03", "2019-05-03", "2019-05-03", "2019-05-03", "2019-06-03", "2019-06-03", "2019-06-03", "2019-06-03", "2019-06-03", "2019-06-03", "2019-06-03", "2019-07-03", "2019-07-03", "2019-07-04", "2019-08-03", "2019-09-05", "2019-09-03", "2019-09-03", "2019-09-06", "2019-09-08", "2019-10-03", "2019-11-03", "2019-11-03", "2019-11-03", "2019-11-03", "2019-11-03", "2019-11-03", "2019-12-03", "2019-12-03")
df <- data.frame(dates=as.Date(d))
現在,我創建一個時間序列圖:
# aggregate data
df_plot <- df %>% mutate(month = lubridate::floor_date(dates, "month")) %>%
group_by(month) %>% summarise(count = n())
# plot data
ggplot(aes(x = month, y = count), data = df_plot) + geom_line() +
scale_x_date() +
geom_vline(xintercept = as.numeric(as.Date("2019-01-30")), linetype=4)
使用geom_vline(xintercept = as.numeric(as.Date("2019-01-30")), linetype=4)
我可以用垂直線標記某個日期。 是否還有可能用彩色框或其他東西標記時間范圍(比如從 2019-01-30 到 2019-02-15)?
將geom_rect
與ymin = -Inf
和ymax = Inf
結合使用。
xmin <- as.Date("2019-01-30")
xmax <- as.Date("2019-02-15")
ggplot(df_plot, aes(month, count)) +
geom_line() +
scale_x_date() +
geom_rect(aes(xmin = xmin, xmax = xmax, ymin = -Inf, ymax = Inf,
alpha = I(.1), fill = I("lightblue"))) +
annotate("text", label = "Some text", x = xmin, y = Inf, angle = 90,
hjust = 1.1, vjust = -1)
(截圖后續)
另一種可能性是創建一個數據框regimes
來保存邊界和標簽。 這與之前的代碼類似,但如果我們必須添加更多的 regimes ,那么只需向regimes
添加行即可。
regimes <- data.frame(xmin = as.Date("2019-01-30"),
xmax = as.Date("2019-02-15"),
label = "Some text")
ggplot(regimes) +
geom_line(aes(month, count), df_plot) +
scale_x_date() +
geom_rect(aes(xmin = xmin, xmax = xmax, ymin = -Inf, ymax = Inf),
alpha = I(.5), fill = I("lightblue")) +
geom_text(aes(x = xmin, y = Inf, label = label), angle = 90,
hjust = 1.1, vjust = -1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.