Search code examples
rfunctionggplot2stat

Does ggplot use dynamic function for statistic functions?


So I'm running an optimization problem and am trying to add the function at each point in time to a plot. I'm able to plot the function but I have the variables stored and it seems like r doesn't evaluate the function until it renders it. It's hard to explain, but I have a simple example that shows it.

data = data.frame(x = runif(20, -10, 10), y = runif(20, -10,10))
p <- ggplot(data, aes(x = x, y =y))
slope = 0.5
yoff = 1
p <- p + stat_function(fun = function(x) slope*x+yoff)
slope = 1
yoff = -1
p <- p + stat_function(fun = function(x) slope*x+yoff)
p

And what I want is two lines on the graph with the slope and y-intercept that I had when I added the function to the graph.


Solution

  • If you have a lot of them, make a list of functions:

    make_fun <- function(slope,yoff) {slope; yoff; function(x) x*slope + yoff}
    > l <- mapply(FUN = make_fun,slope = 1:2,yoff = 3:4)
    > l[[1]](1)
    [1] 4
    > l[[2]](1)
    [1] 6