将多个突破图组合在一起[r]

问题描述 投票:0回答:1

我在r中使用breakout包成功运行了breakoutDetection函数。这个功能的可能产品之一是$ plot。运行breakout后,是否可以组合嵌入列表中的多个图?我尝试过par( )功能但没有成功。在我用ggplot重现时间序列之前的任何想法?

可重复的例子:

require(BreakoutDetection)
df.date = c("01-01-2017", "02-01-2017", "03-01-2017", "04-01-2017", "05-01-2017", "06-01-2017", "07-01-2017", "08-01-2017", "09-01-2017", "10-01-2017")
df.values = c(1,2,1,1,3,22,34,45,22, 10)
ts = data.frame(df.date, df.values)
ts.b = breakout(ts$df.values, min.size=3, method='multi', beta=.008, degree=1, plot=TRUE, xlab = "time")
ts.b$plot

我希望能够将ts.b$plot元素与其他图表(基于其他数据)结合在一个2 * 2矩阵或其他3 * 1矩阵中......另外我想重命名x轴以显示日期而不是整数(按时间序列的大小)

r plot time-series breakout
1个回答
0
投票

如果你去看the source code of this package,它只是使用ggplot2绘制你的df和突破检测输出中的东西。

这是一个跟随代码的工作示例

# your code
require(BreakoutDetection)
df.date = c("01-01-2017", "02-01-2017", "03-01-2017", "04-01-2017", "05-01-2017", "06-01-2017", "07-01-2017", "08-01-2017", "09-01-2017", "10-01-2017")
df.values = c(1,2,1,1,3,22,34,45,22, 10)
ts = data.frame(df.date, df.values)
ts.b = breakout(ts$df.values, min.size=3, method='multi', beta=.008, degree=1, plot=TRUE, xlab = "time")
ts.b$plot



# start:
library(ggplot2)

# the code in this function is copied from the source code of breakout detection (with small adjustment)
# you can adjust things
plot_breakout_detection = function(Z, retList, dateTime = T, x_lab = '', y_lab = '', title0 = ''){

    if(class(Z)%in%c('numeric','integer') || ncol(Z) == 1){
        dateTime = F
        Z = data.frame(timestamp=1:length(Z), count = Z)
    }


    g = ggplot2::ggplot(Z, ggplot2::aes(x=timestamp, y=count)) + ggplot2::theme_bw() + 
        ggplot2::theme(panel.grid.minor=ggplot2::element_blank(), panel.grid.major=ggplot2::element_blank())


    g = g + ggplot2::xlab(x_lab) + ggplot2::ylab(y_lab) + ggplot2::ggtitle(title0)

    g = g + ggplot2::geom_line()

    if(!is.null(retList$loc)&& length(retList$loc)>0){
        v = retList$loc
        v = c(0,v)
        for(j in 2:length(v)){
            M = mean(Z$count[(v[j-1]+1):v[j]])
            df2 = data.frame(Z$timestamp[v[j]], Z$timestamp[v[j]], -Inf, M)
            names(df2) = c('x','xend','y','yend')
            g = g + ggplot2::geom_segment(data=df2,ggplot2::aes(x=x,y=y,xend=xend,yend=yend,color='2'),linetype=2,size=1.2)
            g = g + ggplot2::guides(color=FALSE)
        }
    }

    if(dateTime){
        g = g + scale_x_datetime(expand=c(0,0)) + scale_y_continuous(expand=c(0,0))
    } else {
        g = g + scale_x_continuous(expand=c(0,0)) + scale_y_continuous(expand=c(0,0))
    }

}



df = data.frame(timestamp = as.POSIXct(df.date, format = '%m-%d-%Y'), count = df.values)
g = plot_breakout_detection(df, ts.b)
g

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.