2013-05-02 16 views
2

我已經習慣了這一點,如果我想要一個點添加到ggplot,它工作得很好:如何用新數據添加圖層到具有POSIX軸的ggplot?

ggplot(mtcars, aes(x = disp, y = mpg)) + geom_point() + 
    geom_point(x = 200, y = 20, size = 5, color = "blue") 

但是,我得到的問題,如果有涉及POSIX日期:

dat_1 <- data.frame(time = as.POSIXct(c("2010-01-01", "2010-02-01", "2010-03-01")), 
        y_1 = c(-1, 0, 1)) 

的基本情節的作品,當然

(my_plot <- ggplot(dat_1, aes(x = time, y = y_1)) + 
    geom_point()) 

,但增加另一層

my_plot + geom_point(x = as.POSIXct("2010-01-01"), 
    y = 0, size = 5, color = "blue") 

返回一個錯誤

Error in Ops.POSIXt((x - from[1]), diff(from)) : 
    '/' not defined for "POSIXt" objects 

回答

7

轉換爲數字解決問題:

my_plot + geom_point(x = as.numeric(as.POSIXct("2010-01-01")), 
    y = 0, size = 5, color = "blue") 

但如果映射在一個aes包裝沒有必要

point_data <- data.frame(x = as.POSIXct("2010-01-01"), y = 0) 
my_plot + geom_point(aes(x = x, y = y), data = point_data, 
        size = 5, color = "blue" 
相關問題