如何不使用 R 绘制时间序列中的间隙 [英] How to not plot gaps in timeseries with R

查看:17
本文介绍了如何不使用 R 绘制时间序列中的间隙的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些时间序列数据有差距.

I have some time series data with gaps.

df<-read.table(header=T,sep=";", text="Date;x1;x2
2014-01-10;2;5
2014-01-11;4;7
2014-01-20;8;9
2014-01-21;10;15
")
df$Date <- strptime(df$Date,"%Y-%m-%d")
df.long <- melt(df,id="Date")
ggplot(df.long, aes(x = Date, y = value, fill = variable, order=desc(variable))) +   
  geom_area(position = 'stack') 

现在 ggplot 会填充缺失的日期(12 日、13 日……).我想要的只是 ggplot 不插入丢失的日期而只绘制可用的数据.我已经尝试用合并填充缺失日期的 NA,这会导致删除行的错误消息.

Now ggplot fills in the missing dates (12th, 13th, ...). What I want is just ggplot to not interpolate the missing dates and just draw the data available. I've tried filling NA with merge for the missing dates, which results in an error message of removed rows.

这可能吗?谢谢.

推荐答案

您可以在数据框中添加一个附加变量group,指示两个日期之间的差异是否不等于一天:

You can add an additional variable, group, to your data frame indicating whether the difference between two dates is not equal to one day:

df.long$group <- c(0, cumsum(diff(df.long$Date) != 1))

ggplot(df.long, aes(x = Date, y = value, fill = variable, 
                    order=desc(variable))) +
  geom_area(position = 'stack', aes(group = group)) 

更新:

为了消除组之间的空间,我建议分面:

In order to remove the space between the groups, I recommend facetting:

library(plyr)
df.long2 <- ddply(df.long, .(variable), mutate, 
                  group = c(0, cumsum(diff(Date) > 1)))

ggplot(df.long2, aes(x = Date, y = value, fill = variable, 
                     order=desc(variable)))  +
  geom_area(position = 'stack',) +
  facet_wrap( ~ group, scales = "free_x")

这篇关于如何不使用 R 绘制时间序列中的间隙的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆