简体   繁体   中英

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

I have an R function called stock (below). 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? (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() .

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)

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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