Home > other >  Plotting list of functions using for loop in R
Plotting list of functions using for loop in R

Time:02-01

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))
}

CodePudding user response:

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

CodePudding user response:

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))
}
  • Related