如何使用POSIX轴将具有新数据的图层添加到ggplot?

时间:2013-05-02 17:07:39

标签: r ggplot2

如果我想向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

1 个答案:

答案 0 :(得分: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"