3

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)
aosmith
  • 34,856
  • 9
  • 84
  • 118
Rilcon42
  • 9,584
  • 18
  • 83
  • 167
  • 1
    *ggplot2* is designed to work with data.frames, and the `data` argument is the first one in `ggplot`. If you really don't want to work with data.frames you'll need to name the arguments: `ggplot(mapping = aes(trump_score$Date) )` so you aren't passing the mapping to the `data` argument. Once you have a plot, the `as.numeric` solution for the date in `geom_vline` will work. – aosmith Aug 25 '17 at 20:21
  • Use ggplot2's `annotate` function to draw non-tabular stuff. – Nathan Werth Aug 25 '17 at 20:32

1 Answers1

2

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.

Joanna
  • 663
  • 7
  • 21
  • 1
    I was looking for a solution that would take in a Date, find its position on the x axis (of Dates) and plot it- I will try to make my question clearer – Rilcon42 Aug 29 '17 at 18:42