GGPLOT2时间序列绘制:如何省略周期时,有没有数据点?(ggplot2 time series

2019-07-17 18:57发布

我有一个数据的多天的时间序列。 在每一天之间有一个周期没有数据点。 我怎样才能绘制使用时间序列时,省略这些时期ggplot2

显示一个人为的例子如下,我怎么能摆脱两个时段没有数据?

码:

Time = Sys.time()+(seq(1,100)*60+c(rep(1,100)*3600*24, rep(2, 100)*3600*24, rep(3, 100)*3600*24))
Value = rnorm(length(Time))
g <- ggplot() 
g <- g + geom_line (aes(x=Time, y=Value))
g

Answer 1:

首先,创建一个分组变量。 这里,如果时间差小于1分钟大两个基团是不同:

Group <- c(0, cumsum(diff(Time) > 1))

现在,三个不同的面板可以用创建facet_grid和参数scales = "free_x"

library(ggplot2)
g <- ggplot(data.frame(Time, Value, Group)) + 
  geom_line (aes(x=Time, y=Value)) +
  facet_grid(~ Group, scales = "free_x")



Answer 2:

问题是,如何做GGPLOT2知道你有缺失值? 我看到两个选项:

  1. 垫带出你的时间序列的NA
  2. 添加表示“基团”的附加变量。 例如,

     dd = data.frame(Time, Value) ##type contains three distinct values dd$type = factor(cumsum(c(0, as.numeric(diff(dd$Time) - 1)))) ##Plot, but use the group aesthetic ggplot(dd, aes(x=Time, y=Value)) + geom_line (aes(group=type)) 



Answer 3:

csgillespie由NA提到填充,但更简单的方法是每个块之后添加一个NA:

Value[seq(1,length(Value)-1,by=100)]=NA

其中-1避免了警告。



文章来源: ggplot2 time series plotting: how to omit periods when there is no data points?
标签: r ggplot2