Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot adding vertical line on Date axis

Tags:

date

r

ggplot2

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)
like image 363
Rilcon42 Avatar asked Jun 05 '26 13:06

Rilcon42


1 Answers

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.

like image 87
Joanna Avatar answered Jun 07 '26 23:06

Joanna



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!