2017-08-25 174 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