我想手动将中断添加到带日期的 ggplot2 时间序列图。不幸的是,我没有尝试过。我尝试了以下建议,但它似乎不再适用于更新版本的 ggplot2(正如其他人评论的那样)Breaks for scale_x_date in ggplot2 and R这是一个可重现的例子:
library(gtrends)
library(ggplot2)
library(cowplot)
library(reshape2)
ch <- gconnect(xxx@xxx.com, 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
非常感谢任何帮助。
最佳答案
如果您将休息时间格式化为日期而不是字符串,它应该会起作用。在下面的代码中,我刚刚将 breaks
向量包装在 as.Date()
中:
scale_x_date(breaks = as.Date(c("2016-02-12",'2014-11-10')),
labels = c("Label 1","Label 2"))
关于r - 如何在处理日期时手动向 ggplot2 添加中断?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36950567/