2016-04-30 103 views
1

我想手動添加休息到含日期的ggplot2時間序列圖。不幸的是,我沒有嘗試過。我嘗試了以下建議,但它似乎不再與較新版本的GGPLOT2的工作(如其他人評論)Breaks for scale_x_date in ggplot2 and R這裏是一個重複的例子:如何在使用日期時手動添加中斷到ggplot2?

library(gtrends) 
library(ggplot2) 
library(cowplot) 
library(reshape2) 

ch <- gconnect([email protected], xxxx) 
res<-gtrends(c("NBA"), start_date="2014-01-01") 
trend<-(res$trend) 
trend.m<-melt(trend, id.var=c("start","end")) 
trend.m$date<-as.Date(start) 

ggplot(data=trend.m,aes(x= date,y=value,color=variable))+ 
geom_line(size=0.5) + theme_bw() + 
scale_x_date(date_breaks = "6 month",labels = date_format("%b %y")) 

我試過如下:

ggplot(data=trend.m,aes(x=date,y=value))+geom_line(size=0.5) + 
    theme_bw()+scale_x_date(breaks = c("2016-02-12",'2014-11-10'), 
    labels = c("Label 1","Label 2")) 

這將產生以下錯誤:Error in strsplit(unitspec, " ") : non-character argument

我也試過以下

library(scales) 

ggplot(data=trend.m,aes(x=date,y=value))+geom_line(size=0.5) + 
    theme_bw()+scale_x_date(date_breaks = c("2016-02-12",'2014-11-10'), 
    labels = c("Label 1","Label 2")) 

ggplot(data=trend.m,aes(x=date,y=value))+geom_line(size=0.5) + 
     theme_bw()+scale_x_date(date_breaks = c("2016-02-12",'2014-11-10'), 
     date_labels = c("Label 1","Label 2")) 

這兩者產生這樣的錯誤:

Error in cut.Date(date, time, right = TRUE, include.lowest = TRUE) : 
    invalid specification of 'breaks' 
In addition: Warning message: 
In if (prec$unit == "day") { : 
    the condition has length > 1 and only the first element will be used 

任何幫助十分讚賞。

+0

http://stackoverflow.com/questions/32653730/ggplot2-scale-x-date – Gopala

+0

是啊,我已經試過庫(縮放)(因此爲什麼我加載它的依賴)。沒有工作(產生以下錯誤:''錯誤cut.Date(日期,時間,右= TRUE,include.lowest = TRUE): 的無效規範「遊」 此外:警告消息: 在如果( prec $ unit ==「day」){: 條件長度大於1,只有第一個元素會被使用),這是我的默認假設,所以我查了一下''help ''scale_x_date()'函數,我遵循了我發佈的那個建議。 –

+1

嘗試在as.Date()中包裝日期符號向量。 – eipi10

回答

1

,如果你格式化你的假期,因爲日期,而不是作爲字符串它應該工作。在下面的代碼,我剛剛結束了breaks向量as.Date()

scale_x_date(breaks = as.Date(c("2016-02-12",'2014-11-10')), 
      labels = c("Label 1","Label 2"))