How to not plot gaps in timeseries with R

…衆ロ難τιáo~ 提交于 2019-11-27 19:37:32

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/21529332/how-to-not-plot-gaps-in-timeseries-with-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!