【问题标题】:geom_vlines multiple vlines per plotgeom_vlines 每个图有多个 vlines
【发布时间】:2015-08-30 01:37:48
【问题描述】:

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

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

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

您能否指出我正确的方向,为什么我在前 2 个图中只得到 vlines

【问题讨论】:

  • 我更新了问题
  • 如果你安装 R 包 ecp 应该可以复制/粘贴代码。
  • 我更新了问题——ecp 的部分现在正在工作,我得到了一些简单的 vlines 但仅在部分地块中
  • 正如stackoverflow.com/questions/25486994/… 所示,我必须将其更改为:xintercept=variable 但这会导致离散值提供给连续比例

标签: r ggplot2 time-series timeserieschart


【解决方案1】:

这是解决方案:

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')

【讨论】:

猜你喜欢
  • 2023-03-24
  • 2021-05-15
  • 2020-08-29
  • 2016-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-06
  • 1970-01-01
相关资源
最近更新 更多