4

I try to include a vertical line in a graph with dates on the x-axis. The position of the line shall be determined by a certain date. I cannot however manage to control the position by the date itself but only by the position/line of the date in the dataset. As additional lines might enter the dataset at a later point in time, I look for a solution using the date instead of its' position.

Here some Dummy Data to illustrate my problem & approach:

library(ggplot2)
#Setting up of Dummy Data
Dummy_date<-seq(as.Date("2017-01-01"),as.Date("2017-06-01"),by="days")
Dummy_data<-seq(1:152)
Dummy_df<-as.data.frame(cbind(Dummy_date,Dummy_data))
names(Dummy_df[1])<-"Date"
names(Dummy_df[2])<-"Data"

#Format Dates
Dummy_df$Dummy_date<-as.POSIXct(Dummy_date)

#Does not work but is the desired approach
ggplot(Dummy_df)+
 geom_point(mapping=aes(x=Dummy_date,y=Dummy_data))+
 geom_vline(aes(xintercept=as.numeric(as.Date("2017-04-01"))),type=4,col="red")

#Works but I do not like the fixed position[91] in the dataset. Line 91 contains the relevant date
 ggplot(Dummy_df)+
 geom_point(mapping=aes(x=Dummy_date,y=Dummy_data))+
 geom_vline(aes(xintercept=as.numeric(Dummy_date[91])),type=4,col="red")

Thanks in advance

Dr. Jones
  • 141
  • 1
  • 10

1 Answers1

6

Not sure why tbh, but casting as.POSIXct instead of as.Date get you what you want:

library(ggplot2)

ggplot(Dummy_df) +
    geom_point(aes(Dummy_date, Dummy_data)) +
    geom_vline(aes(xintercept = as.integer(as.POSIXct("2017-04-01"))), col = "red")

PS, use linetype instead of type

GGamba
  • 13,140
  • 3
  • 38
  • 47
  • According to [this](https://stackoverflow.com/questions/5388832/how-to-get-a-vertical-geom-vline-to-an-x-axis-of-class-date?noredirect=1&lq=1) old post there is a Google Groups post about this issue. At any rate, vlines inability to use date formats is a known [issue](https://github.com/tidyverse/ggplot2/issues/1048). – Jeff Parker Aug 08 '17 at 20:18