r - 如何在处理日期时手动向 ggplot2 添加中断?

标签 r date ggplot2

我想手动将中断添加到带日期的 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/

相关文章:

r - 使用 with par(mfrow=c()) 在一张图中绘制多个 fill.contour 图

R中的残差使用auto.arima和预测包

date - getline,awk和日期(格式化日期)

r - ggmap 无法绘制特定区域

R - tidyr - 变异并传播多列

R - 逻辑回归 - 模型预测和分割数据的情况非常糟糕。有想法吗?

sql - 如何将日期和时间组合成 db2 中的时间戳?

mysql - 使用 MySQL 按年和月分组,同时利用索引并避免临时/文件排序

r - 存在 2 个图例时如何更改图例点的大小

r - 使用因子将 ggplot 中的标签拆分为 2 行