2015-08-21 26 views
0

我有一個不完整的時間序列這意味着有很大的差距的意見:繪製多條線路有間隙(不完整的時間序列)

dat <- data.frame(
    date = c(2000, 2001, 2002, 2009, 2010, 2011), 
    value1 = runif(6,1,100), 
    value2 = runif(6,1,100) 
) 
library("reshape2") 
dat_long <- melt(dat, id="date") 
dat_long$time <- ifelse(dat_long$date < 2009, "early", "late") 

我想用ggplot2繪製dat,但有2002年和2009年的意見之間存在差距。實際上,應該有兩組生產線:一組爲2000年,2001年和2002年,另一組爲2009年,2010年和2011年(因此按time分組)。

Line break when no data in ggplot2,我試圖

library("ggplot2") 
ggplot(data=dat_long, aes(x=date, y=value, group=variable)) + 
    geom_line(aes(color=variable, group=time)) + 
    geom_point(aes(color=variable)) 

但這只是結合了所有的要點:

All points combined

我的問題和Line break when no data in ggplot2之間的區別是,我有多個行,這顯然禁止在我的geom_line(aes(...))調用中使用group=time

然後我試圖方面作爲第二最佳解決方案:

ggplot(data=dat, aes(x=date, y=value, group=variable)) + 
    geom_line() + geom_point() + facet_grid(~ time) 

但是,即使沒有觀察由此得出沿x軸的整個規模: Facet

+1

嘗試'ggplot(data = merge(x = data.frame(data_date = seq(min(dat [,1]),max(dat [,1]))),y = dat,all.x = TRUE),aes(x = data_date,y = data_value))+ geom_line()+ geom_point()'。 – lukeA

+3

您可以將'scales =「free_x」'添加到您的'facet_grid'調用中。 – nrussell

+0

即使是一個包裝,尤其是那些有差距的數據,還沒有包裝嗎? – maj

回答

1

你可以使用一個新的變量爲等於變量+時間(即,四個組:價值1-早,價值1-遲,價值2-早,價值2-遲)enter image description here