2017-08-25 139 views
1

我想在日期轴上的特定日期添加垂直线。根据this SO post,我似乎需要将日期转换为数字,但这不适用于我。我究竟做错了什么?在日期轴上添加垂直线的ggplot

我的错误:

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

我的代码

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

* ggplot2 *设计用于处理data.frames,'data'参数是'ggplot'中的第一个参数。如果你真的不想使用data.frames,你需要命名参数:'ggplot(mapping = aes(trump_score $ Date))',所以你不会将映射传递给'data'参数。一旦你有了一个情节,'geom_vline'中日期的'as.numeric'解决方案将会工作。 – aosmith

+0

使用ggplot2的'annotate'函数来绘制非表格的东西。 –

回答

0

这里是我的代码:

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) 

顺便说一句,我不知道如果xintercept()是最好的方式添加一行,因为您的添加剂行不符合“trump_score”日期框中的任何Date日期列。

如果您有任何问题,请让我知道。

+0

我一直在寻找一种解决方案,它将采用日期,在x轴(日期)上找到它的位置并绘制它 - 我会尽量使问题更清晰 – Rilcon42