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

4.1k views Asked by At

I have looked at a number of solutions to others' problems relating to the same issues, but nothing thus far has worked for me.

I want a vertical line to appear on "2018-07-23" and this code is the closest I have gotten (in that it doesn't produce an error):

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

The format of grouped$date is character, which is why I convert it to date. Note that I get the same (non-)result with as.POSIXct too.

Where am I going wrong?

My data frame:

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

My graph:

enter image description here

2

There are 2 answers

1
AlienDeg On BEST ANSWER

How about changing xintercept = as.Date(grouped$date[8]) to 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")

enter image description here

1
heck1 On

Reproduced your plot with your example and casted the grouped$date as.Date in all instances and it worked fine:

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

Out comes the plot: https://i.stack.imgur.com/yFDSG.jpg