rnorouzian
rnorouzian

Reputation: 7517

How to provide an initial plotting platform to add additional plots in R?

I'm trying to use a for loop to draw 3 side by side curves in R but without getting any error message nothing shows?

I suspect something should provide an initial plotting platform for the first curve, and then the second and the third plots can be added. Can the initial plotting platform be plot.new() for example?

Note: I'm definitely trying to avoid using long if else statements as a solution.

Here is my R code:

for(i in 1:3){

  p = c(.1, .5, .9)[i]
col = c("red3", "green3", "blue")[i]

curve( dbinom(x, size = 100, prob = p), add = T, ty = "h", xlim = c(0, 100), 
   col = col, xlab = "Number of Agreements", ylab = "Probability", las = 1 )

}

Upvotes: 0

Views: 70

Answers (3)

rnorouzian
rnorouzian

Reputation: 7517

What worked for me was the following:

for(i in 1:3){

  p = c(.1, .5, .9)[i]
col = c("red3", "green3", "blue")[i]

curve( dbinom(x, size = 100, prob = p), 0, 100, add = ifelse(i > 1, T, F), ty = "h", xlim = c(0, 100), 
   col = col, ylab = "Probability", xlab = "Number of Agreements", las = 1)
}

Upvotes: 0

Matt Tyers
Matt Tyers

Reputation: 2215

Since you'd like to avoid if statements, how about

p = c(.1, .5, .9)
col = c("red3", "green3", "blue")

for(i in 1:3) curve(dbinom(x, size = 100, prob = p[i]), add = i!=1, 
    ty = "h", xlim = c(0, 100), col = col[i], 
    xlab = "Number of Agreements", ylab = "Probability", las = 1 )

Upvotes: 1

Vitor Quix
Vitor Quix

Reputation: 174

The first insertion occurs error because the curve does not exist. If you want a simple solution, follow the one below:

for(i in 1:3){

  if(i == 1){
  p = c(.1, .5, .9)[i]
  col = c("red", "green", "blue")[i]

  curve( dbinom(x, size = 100, prob = p), ty = "h", xlim = c(0, 100), 
         col = col, xlab = "Number of Agreements", ylab = "Probability", las = 1 )
  }else{
    p = c(.1, .5, .9)[i]
    col = c("red", "green", "blue")[i]

    curve( dbinom(x, size = 100, prob = p), add = T, ty = "h", xlim = c(0, 100), 
           col = col, xlab = "Number of Agreements", ylab = "Probability", las = 1 )
  }

}

Upvotes: 0

Related Questions