I want to add multiple curves to one ggplot. With the normal plot and curve(add=TRUE) i can loop the curve function and can add multip
Try:
library(ggplot2)
add_curve <- function(plot, i) {
return(plot + stat_function(aes(x=1:200),fun = function(x) {x+i*3}, col=i))
}
p1 <- ggplot()
for (i in 1:10){
p1<- add_curve(p1, i)
}
p1
Output is:
Or alternatively you can also define your function inside the for-loop:
for (i in 1:10){
add_curve <- function(plot, i) {
return(plot + stat_function(aes(x=1:200),fun = function(x) {x+i*3}, col=i))
}
p1<- add_curve(p1, i)
}
Or as a (somewhat obscure) Reduce + lapply one-liner (thx to @KonradRudolph):
eval(
Reduce(function(a, b) call('+', a, b),
lapply(1:10, function(i) {
bquote(stat_function(aes(x=1:200),fun = function(x) {x+.(i)*3
}, col=.(i)))}), init = quote(ggplot())))
The idea is to build the whole ggplot() call at once and then evaluate it.