简体   繁体   English

在上一个R函数运行的图上绘制线段

[英]Plotting line segments on top of a plot from a previous run of an R function

I have an R function called stock (below). 我有一个称为stockR函数(如下)。 I was wondering if it might be in any way possible that the result of each run of the function (which is a plot() ) be plotted (ie, added) on top of the plot from the previous run of the function? 我想知道是否可以以任何方式将函数的每次运行(这是plot() )的结果绘制(即添加)到函数上一次运行的图的顶部? (the picture below the code may show this) (代码下面的图片可能显示了这一点)

stock = function(m, s){

 loop = length(s) 

 I = matrix(NA, loop, 2)

for(i in 1:loop){
I[i,] = quantile(rbeta(1e2, m, s[i]), c(.025, .975))
 }
plot(rep(1:loop, 2), I[, 1:2], ty = "n", ylim = 0:1, xlim = c(1, loop))

segments(1:loop, I[, 1], 1:loop, I[, 2])
}
# Example of use:
stock(m = 2, s = c(1, 10, 15, 20, 25, 30))
stock(m = 50, s = c(1, 10, 15, 20, 25, 30)) #The result of this run be plotted on top of previous run above

在此处输入图片说明

Simplest would be to add an argument for the option. 最简单的方法是为该选项添加一个参数。 As segments() by default adds to the previous frame, all you have to do is to not do a new plot() . 默认情况下, segments()添加到前一帧,因此您要做的就是不做新的plot()

stock = function(m, s, add=FALSE) {

    loop = length(s) 
    I = matrix(NA, loop, 2)

    for(i in 1:loop) {
        I[i,] = quantile(rbeta(1e2, m, s[i]), c(.025, .975))
    }
    if (!add) {
        plot(rep(1:loop, 2), I[, 1:2], ty = "n", ylim = 0:1, xlim = c(1, loop))
    }
    segments(1:loop, I[, 1], 1:loop, I[, 2], xpd = NA)
}

# Example of use:
set.seed(1)
stock(m = 2, s = c(1, 10, 15, 20, 25, 30))
stock(m = 50, s = seq(1, 90, 10), add=TRUE)

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM