0

How can you plot a list of functions in one graph using a for loop in R? The following code does the trick, but requires a separate call of plot for the first function outside of the for loop, which is very clunky. Is there a way to handle all the plotting inside the for loop without creating multiple plots?

vec <- 1:10
funcs <- lapply(vec, function(base){function(exponent){base^exponent}})

x_vals <- seq(0, 10, length.out=100)
plot(x_vals, funcs[[1]](x_vals), type="l", ylim=c(0,100))
for (i in 2:length(vec)) {
  lines(x_vals, funcs[[i]](x_vals))
}
2
  • You still need the first function to define the x and y limits. Base R plots don't update the view region when you add additional elements. Would you rather use something like ggplot instead of base R? Commented Jan 31, 2023 at 21:36
  • @MrFlick Thanks! Maybe I ought to switch to ggplot, I just like keeping imports to a minimum, but only so much can be done. I think I just found a work-around, I'll post it as an answer below. Commented Jan 31, 2023 at 21:39

2 Answers 2

2

You can also do the computations first and plotting after, like this:

vec <- 1:10
funcs <- lapply(vec, function(base) function(exponent){base^exponent})

x_vals <- seq(0, 10, length.out=100)
y_vals <- sapply(funcs, \(f) f(x_vals))
plot(1, xlim=range(x_vals), ylim=range(y_vals), type='n', log='y', 
     xlab='x', ylab='y')
apply(y_vals, 2, lines, x=x_vals)

This way you know the range of your y values before initiating the plot and can set the y axis limits accordingly (if you would want that). Note that I chose to use logarithmic y axis here.

R plot

Sign up to request clarification or add additional context in comments.

Comments

0

Based on MrFlick's comment, it looks like something like this would be one way to do what I'm looking for, but is still not great.

vec <- 1:10
funcs <- lapply(vec, function(base){function(exponent){base^exponent}})

x_vals <- seq(0, 10, length.out=100)
plot(NULL, xlim=c(0,10), ylim=c(0,100))
for (i in 1:length(vec)) {
  lines(x_vals, funcs[[i]](x_vals))
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.