3

我想在同一个面板图上绘制多个时间序列,而不是在单独的面板中。我从另一个 stackoverflow 帖子中获取了以下 R 代码。

请注意 3 个时间序列如何在 3 个不同的面板中。我如何能够在 1 个面板上分层 3 个时间序列,并且每条线的颜色可能不同。

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))
Group = c(0, cumsum(diff(Time) > 1))

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

如果你运行上面的代码,你会得到:

在此处输入图像描述

facet_grid()零件被消除时,我得到一个如下所示的图表:

ggplot坏图

基本上,我希望 ggplot 忽略日期的差异,只考虑时间。然后用它group来识别不同的日期。

这个问题可以通过创建一个只包含时间的新列来解决(例如22:01,,format="%H:%M")。但是,当as.POSIXct()使用函数时,我得到一个包含日期和时间的变量。我似乎无法逃避日期部分。

4

1 回答 1

4

由于数据文件对于每个组的时间有不同的日期,将所有组放到同一个图上的一种方法是创建一个新变量,为所有组提供相同的“虚拟”日期,但使用收集的实际时间。

experiment <- data.frame(Time, Value, Group)  #creates a data frame
experiment$hms <- as.POSIXct(paste("2015-01-01", substr(experiment$Time, 12, 19)))  # pastes dummy date 2015-01-01 onto the HMS of Time

现在您有了所有相同日期的时间,然后您可以轻松地绘制它们。

experiment$Grouping <- as.factor(experiment$Group)  # gglot needed Group to be a factor, to give the lines color according to Group
ggplot(experiment, aes(x=hms, y=Value, color=Grouping)) + geom_line(size=2)

下面是生成的图像(您可以根据需要更改/修改基本图): 在此处输入图像描述

于 2015-10-06T20:23:05.607 回答