2016-03-07 41 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()