为什么我的 geom_vline 对象没有出现在我的绘图中?

Why doesn't my geom_vline object show up on my plot?

我已经查看了很多解决其他人遇到的相同问题的方法,但到目前为止没有一个对我有用。

我想要一条竖线出现在“2018-07-23”上,这段代码是我得到的最接近的代码(因为它不会产生错误):

ggplot(grouped) +
  geom_line(aes(x = date, y = sitewide_opens, group = 1),
            linetype = "dashed",
            colour = "forestgreen",
            alpha = 0.5) +
  geom_line(aes(x = date, y = homepage_opens, group = 1),
            colour = "blue") +
  geom_vline(aes(xintercept = as.Date(grouped$date[8])),
             linetype = 4, colour = "black")

grouped$date的格式是字符,所以我把它转换成日期。请注意,我也使用 as.POSIXct 得到相同的(非)结果。

我哪里错了?

我的数据框:

grouped <- structure(list(date = c("2018-07-16", "2018-07-17", "2018-07-18", 
"2018-07-19", "2018-07-20", "2018-07-21", "2018-07-22", "2018-07-23", 
"2018-07-24", "2018-07-25", "2018-07-26", "2018-07-27", "2018-07-28", 
"2018-07-29", "2018-07-30", "2018-07-31"), homepage_opens = c(5L, 
0L, 0L, 3L, 1L, 2L, 0L, 1L, 0L, 2L, 5L, 0L, 0L, 0L, 0L, 0L), 
    sitewide_opens = c(39L, 34L, 19L, 62L, 46L, 44L, 16L, 51L, 
    25L, 66L, 75L, 0L, 0L, 0L, 0L, 0L), chats_started = c(10L, 
    16L, 9L, 8L, 13L, 13L, 5L, 13L, 4L, 8L, 11L, 0L, 0L, 0L, 
    0L, 0L), chats_completed = c(7L, 13L, 8L, 4L, 5L, 9L, 6L, 
    13L, 2L, 7L, 5L, 0L, 0L, 0L, 0L, 0L)), class = c("tbl_df", 
"tbl", "data.frame"), row.names = c(NA, -16L))

我的图表:

如何将 xintercept = as.Date(grouped$date[8]) 更改为 xintercept = 8

ggplot(grouped) +
  geom_line(aes(x = date, y = sitewide_opens, group = 1),
            linetype = "dashed",
            colour = "forestgreen",
            alpha = 0.5) +
  geom_line(aes(x = date, y = homepage_opens, group = 1),
            colour = "blue") +
  geom_vline(aes(xintercept = 8),
             linetype = 4, colour = "black")

用你的例子重现了你的情节,并在所有情况下都投射了 grouped$date as.Date 并且效果很好:

ggplot(grouped) +
  geom_line(aes(x = as.Date(grouped$date), y = sitewide_opens, group = 1),
        linetype = "dashed",
        colour = "forestgreen",
        alpha = 0.5) +
        geom_line(aes(x =  as.Date(grouped$date), y = homepage_opens, group = 1),
        colour = "blue") +
       geom_vline(aes(xintercept = as.Date(grouped$date[8])),
         linetype = 4, colour = "black")

剧情出来了: https://i.imgur.com/Km8UvaX.jpg