Gabriela Facio
Gabriela Facio

Reputation: 13

Plot different colors using for loop

I'm new in R and I have been trying to plot 4 exponential curves with different colors. I want to know how to do it with a for loop.

par(mfrow = c(2, 2))
colors<-rainbow(4)
parameters <- c(10, .25, 1, 6)
for(lambda in parameters){ 
curve(dexp(x, lambda), 0, 3, main = bquote(lambda ==.(lambda)),
font.main = 1, xlab = "x", ylab = "f(x)",col=colors[lambda])
}

Upvotes: 0

Views: 271

Answers (1)

Brian Davis
Brian Davis

Reputation: 992

You were passing your parameter values to index your color object. Generally it's good practice to use 1:n integers in your for loops.

Try this:

for(lambda in seq_along(parameters)){ 
   curve(dexp(x, parameters[lambda]), 0, 3, main = bquote(parameters[lambda] ==.(parameters[lambda])),
         font.main = 1, xlab = "x", ylab = "f(x)",col=colors[lambda])
}

Upvotes: 1

Related Questions