2016-03-07 72 views
0

我正在试图使用geom_rect来遮蔽时间序列图的某个区域。如何使用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_rectfollowing 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) 

我得到这个错误

Error: Invalid input: date_trans works with objects of class Date only

任何矩形建议如何解决这将不胜感激。

+2

刚刚摆脱了'decimal_date的()'。请参阅G.Gotothendieck对你的链接问题的评论:*还要注意,它不是ggplot,它需要这里使用的表格的日期,而是'ts'数据有它们。如果问题提供了'Date'类数据,那么ggplot可以通过'scale_x_date'使用它。* – Gregor

回答

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()