Rilcon42
Rilcon42

Reputation: 9763

ggplot adding vertical line on Date axis

I am trying to add a vertical line at a specific date on an axis of Dates. Based on this SO post it seems that I need to cast the Date as numeric, however that doesn't work for me. What am I doing wrong?

My error:

Error: ggplot2 doesn't know how to deal with data of class uneval

My code

library(lubridate)
trump_score<-NULL
trump_score$Date <-parse_date_time(c("2017-01-01","2017-01-24","2017-01-25"), orders="ymd")

trump_score$powerSentimentScore<-c(10,25,10)
denyTPP<-parse_date_time("2017-01-23", orders="ymd ")

require(ggplot2)
ggplot( aes(trump_score$Date))+
  geom_line(aes(y=trump_score$powerSentimentScore),colour="green")+
  geom_vline(aes(xintercept = as.POSIXct(as.Date(denyTPP))), linetype="dotted", color = "blue", size=1.5)

Upvotes: 3

Views: 4169

Answers (1)

Joanna
Joanna

Reputation: 673

Here is my code:

library(lubridate)
trump_score<-NULL
trump_score$Date <-parse_date_time(c("2017-01-01","2017-01-24","2017-01-25"), orders="ymd")

trump_score$powerSentimentScore<-c(10,25,10)
denyTPP<-parse_date_time("2017-01-23", orders="ymd ")

trump_score2<-data.frame(trump_score)
trump_score2$Date<-as.Date(trump_score2$Date)

require(ggplot2)
ggplot(trump_score2, aes(Date, powerSentimentScore))+
geom_line(colour="green")+
geom_vline(aes(xintercept=as.numeric(Date[c(2)]) ), linetype="dotted", color = "blue", size=1.5)

By the way, I am not sure if xintercept() is the best way to add a line because your additive line is not matching any of your Date col in "trump_score" date frame.

Please let me know if you have any question.

Upvotes: 2

Related Questions