[英]How do I make R lattice xyplot ignore gaps in time and make a continuous timeseries plot?
[英]How to not plot gaps in timeseries with 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$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,這導致刪除行的錯誤消息。
這可能嗎? 謝謝。
您可以向數據框添加一個附加變量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))
更新 :
為了消除組之間的空間,我建議使用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")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.