I am trying to build a user-defined function which basically returns a ggplot of multiple function curves in a single plot. The plot will be a complex version of the plot below, which basically plots 4 curves in one plot:
library(ggplot2)
p <- ggplot() + xlim(0,4) + xlab("x")
p <- p + geom_function(fun = function(x) 1*x)
p <- p + geom_function(fun = function(x) 2*x)
p <- p + geom_function(fun = function(x) 3*x)
p <- p + geom_function(fun = function(x) 4*x)
p
Unfortunately, I am not being able to plot it using a user defined function as below. It only returns me the last plot, out of the four plots:
plot_func <- function(i) {
p <- ggplot() + xlim(0,i) + xlab("x")
for (i in 1:i) {
p <- p + geom_function(fun = function(x) i*x)
}
print(p)
}
plot_func(4)
Can anyone please tell me how to plot this using a user-defined function?
Thank you very much!!
Thanks for your response!! Sorry if I was not clear enough with the question but I want to achieve the plot using a for loop inside a user-defined function, as mentioned in the second set of codes in my question.
With a for loop, it's easy to over-write all the previous values with the last value through the loop. Remember that the intermediate value do not get saved to the global environment unless explicitly assigned to an external object.
Here's an approach similar to technocrat (function factory and purrr::map style looping)
but based on the idea of concretizing the data (i.e. you might export the data as well as plot it)
the plotting can then be simpler as it directly plots the data its provided rather than calculating 'on the fly'