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

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

问题描述

  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 $日期< - 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)))+ $ bg






$ b $现在ggplot填补缺失日期(第12, 13日,...)。我想要的只是ggplot不插入缺失的日期,只是绘制可用的数据。我已经试过用缺失的日期合并NA来合并,这会导致删除行的错误消息。



这可能吗?感谢。

解决方案

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

  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))



< hr>

更新



为了消除组之间的空间,我建议使用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 =变量,
orde r = desc(variable)))+
geom_area(position ='stack',)+
facet_wrap(〜group,scales =free_x)


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') 

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.

Is this possible? Thanks.

解决方案

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)) 


Update:

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天全站免登陆