2015-10-06 170 views
3

組我想繪製在同一個面板圖形幾個時間序列,而不是獨立的面板。我從another stackoverflow post獲取了下面的R代碼。ggplot時間序列繪製:按日期

請注意3個時間序列是如何在3個不同的面板。我將如何在1 panal上對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") 

如果你運行上面的代碼,你會得到這樣的:

enter image description here

facet_grid()部分被淘汰,我得到類似如下的圖表:

ggplot bad graph

基本上,我想ggplot忽略日期的差異,只考慮時間。然後用group來確定不同的日期。

通過創建僅包含時間的新列(例如,22:01,format="%H:%M"),可能會解決此問題。但是,使用as.POSIXct()函數時,我得到一個包含日期和時間的變量。我似乎無法逃避日期部分。

回答

3

由於數據文件有不同的日子裏每個組的時候,一個方式來獲得所有組到同一個情節是隻創建一個新的變量,給所有組相同的「虛擬」的日期,但使用收集到的實際時間。

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) 

以下是得到的圖像(你可以改變/修改的基本情節,你認爲合適): enter image description here