如何使用geom_rect对某个时间序列图区域进行着色?

时间:2016-03-07 22:51:27

标签: r ggplot2 time-series

我正在尝试使用geom_rect对时间序列图的某个区域进行着色。

我使用下面的代码创建时间序列图

library(ggplot2)

set.seed(123)
date <- as.Date(seq(as.Date("2014-01-01"), as.Date("2015-12-31"), by = 1), format="%Y-%m-%d")
a <- runif(730, 3000, 120000)
df <- data.frame(date, a)

ggplot() +
    geom_line(data = df, aes(x = date, y = a))

我尝试使用geom_rect following the answer to this question

创建矩形
library(lubridate)
rectangle <- data.frame(xmin = decimal_date(as.Date(c("2014-10-01"))),
                        xmax = decimal_date(as.Date(c("2015-02-01"))),
                        ymin = -Inf, ymax = Inf)
ggplot() +
    geom_line(data = df, aes(x = date, y = a)) +
    geom_rect(data = rectangle, aes(xmin=xmin, xmax = xmax, ymin = ymin, ymax = ymax),
        fill = "red", alpha = 0.5)

我收到了这个错误

  

错误:输入无效:date_trans仅适用于类Date的对象

任何建议如何解决这一问题将不胜感激。

1 个答案:

答案 0 :(得分:1)

这有效:

library(lubridate)
rectangle <- data.frame(xmin = as.Date(c("2014-10-01")),
                        xmax = as.Date(c("2015-02-01")),
                        ymin = -Inf, ymax = Inf)
ggplot() +
    geom_line(data = df, aes(x = date, y = a)) +
    geom_rect(data = rectangle, aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax),
                              fill = "red", alpha = 0.5)

只需删除decimal_date()

即可
相关问题