Pablowa
Pablowa

Reputation: 73

using ggplots stat_function in a custom function

I am trying to create some ggplots automaticly. Here is my working code example for adding stat_functions:

require(ggplot2)

p1 <- ggplot(data.frame(x = c(-2.5, 7.5)), aes(x = x)) + theme_minimal()+
  stat_function(fun= function(x){1*x},lwd=1.25, colour = "navyblue") + 
  stat_function(fun= function(x){2*x},lwd=1.25, colour = "navyblue") + 
  stat_function(fun= function(x){3*-x},lwd=1.25, colour = "red")
p1

As you can see the stat_functions all use (nearly) the same function just with a different parameter. Here is what i have tried to write:

f <- function(plot,list){
  for (i in 1:length(list)){
    plot <- plot + stat_function(fun= function(x){x*list[i]})
  }
  return(plot)
}

p1 <- ggplot(data.frame(x = c(-2.5, 7.5)), aes(x = x)) + theme_minimal()

p2 <- f(p1,c(1,2,3))
p2

This however doesnt return 3 lines, but only one. Why?

Upvotes: 1

Views: 707

Answers (2)

tjebo
tjebo

Reputation: 23797

Keep the ggplot main object separate and create a list of additional objects, very easy for example with lapply. Add this list to your main plot as usual.

Check also https://ggplot2-book.org/programming.html

library(ggplot2)
p <- ggplot(data.frame(x = c(-2.5, 7.5)), aes(x = x)) + theme_minimal()

ls_sumfun <- lapply(1:3, function(y){
  stat_function(fun= function(x){y*x}, lwd=1.25, colour = "navyblue")
}
)

p + ls_sumfun

Created on 2021-04-26 by the reprex package (v2.0.0)

Upvotes: 4

dash2
dash2

Reputation: 2262

In R, you can pass functions as arguments. You can also return functions from functions. This might make your code simpler and cleaner.

Here's an example:

p1 <- ggplot(data.frame(x = c(-2.5, 7.5)), aes(x = x))

add_stat_fun <- function (ggp, f) {
  ggp + stat_function(fun = f) 
}

make_multiply_fun <- function (multiplier) {
  force(multiplier) # not sure if this is required...
  f <- function (x) {multiplier * x}
  return(f)
}

my_funs <- lapply(1:3, make_multiply_fun)
# my_funs is now a list of functions

add_stat_fun(p1, my_funs[[1]])
add_stat_fun(p1, my_funs[[2]])
add_stat_fun(p1, my_funs[[3]])

Upvotes: 0

Related Questions