geom_vlines每个情节的多个vlines

时间:2015-06-14 13:58:53

标签: r ggplot2 time-series timeserieschart

我怎样才能让ggplot产生类似的东西 Example

library(ggplot2)
library(reshape2)
library(ecp)

synthetic_control.data <- read.table("/path/synthetic_control.data.txt", quote="\"", comment.char="")
n <- 2

s <- sample(1:100, n)
idx <- c(s, 100+s, 200+s, 300+s, 400+s, 500+s)
sample2 <- synthetic_control.data[idx,]
df = as.data.frame(t(as.matrix(sample2)))

#calculate the change points
changeP <- e.divisive(as.matrix(df[1]), k=8, R = 400, alpha = 2, min.size = 3)
changeP = changeP$estimates
changeP = changeP[-c(1,length(changeP))]

changePoints = data.frame(changeP,variable=colnames(df)[1])
for(series in 2:ncol(df)){
  changeP <- e.divisive(as.matrix(df[series]), k=8, R = 400, alpha = 2, min.size = 3)
  changeP = changeP$estimates
  changeP = changeP[-c(1,length(changeP))]
  changePoints = rbind(changePoints, data.frame(changeP,variable=colnames(df)[2]))
}

这是关于情节的有趣部分:

df $ id = 1:nrow(df) dfMelt&lt; - reshape2 :: melt(df,id.vars =“id”) p = ggplot(dfMelt,aes(x = id,y = value))+ geom_line(color =“steelblue”)+ facet_grid(变量〜。,scales ='free_y') p + geom_vline(aes(xintercept = changeP),data = changePoints,linetype ='dashed')

到目前为止,我的结果是:https://www.dropbox.com/s/mysadkruo946oox/changePoint.pdf这意味着我的数组传递给geom_vlines时出现了问题。

你能否指出我正确的方向为什么我只能在前2个地块中获得vlines

1 个答案:

答案 0 :(得分:0)

这是解决方案:

library(ggplot2)
library(reshape2)
library(ecp)

synthetic_control.data <- read.table("/Users/geoHeil/Dropbox/6.Semester/BachelorThesis/rResearch/data/synthetic_control.data.txt", quote="\"", comment.char="")
n <- 2

s <- sample(1:100, n)
idx <- c(s, 100+s, 200+s, 300+s, 400+s, 500+s)
sample2 <- synthetic_control.data[idx,]
df = as.data.frame(t(as.matrix(sample2)))

#calculate the change points
changeP <- e.divisive(as.matrix(df[1]), k=8, R = 400, alpha = 2, min.size = 3)
changeP = changeP$estimates
changeP = changeP[-c(1,length(changeP))]

changePoints = data.frame(changeP,variable=colnames(df)[1])
for(series in 2:ncol(df)){
  changeP <- e.divisive(as.matrix(df[series]), k=8, R = 400, alpha = 2, min.size = 3)
  changeP = changeP$estimates
  changeP = changeP[-c(1,length(changeP))]
  changePoints = rbind(changePoints, data.frame(changeP,variable=colnames(df)[series]))
}

# plot
df$id = 1:nrow(df)
dfMelt <- reshape2::melt(df, id.vars = "id")
p = ggplot(dfMelt,aes(x=id,y=value))+geom_line(color = "steelblue")+ facet_grid(variable ~ ., scales = 'free_y')
p + geom_vline(aes(xintercept=changeP), data=changePoints, linetype='dashed', colour='darkgreen')