1

I have been struggling with the following issue. I want to create a graph using ggplot, superimposing some observed datapoints and estimated functions in one and the same graph. The problem is that I want to plot many functions in the same graph, with parameters stored in a df pars. I would thus need to use a loop both to define the functions, and to add them to the plot.

I have been thinking along the following lines, but all attempts have failed so far:

d <- data.frame(xvar  = c( 0.1 , 0.12 , 0.5 , 0.88, 0.9 ),
                yvar = c( 0.2 , 0.24 , 0.6 , 0.76, 0.8) )  

pars <- data.frame(a = c(0.77,0.56,0.48,0.98,0.67,0.87),
                   b = c(20.3, 15.6, 38, 27.7 , 19.8 , 23.4),
                   row = c(1,2,3,4,5,6))


for (i in 1:n){
fun[i] <- function(x) ( x^pars$a[row==i] + 1/(x*pars$b[row==i]) )
}

d %>%
  ggplot() +
  geom_point(aes(x=xvar , y=yvar)) +
  for (i in 1:n){
    stat_function( fun = fun[i] )
  }

Any ideas how this could be done?

  • It would be easier to help you if you provide [a minimal reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) including a snippet of your data or some fake data so that one can run your code and figure out a solution for your issue. – stefan Jan 04 '23 at 12:01
  • 1
    Point taken. I have added some fake data that should do the trick. – Max Montana Jan 04 '23 at 12:16

1 Answers1

0

As a kind of general rule if you want to add layers using a loop then use lapply or the purrr::map family of functions.

In your case I would go for purrr::pmap which allows to loop over the rows of you paramter dataframe:

library(ggplot2)

ggplot(d) +
  geom_point(aes(x=xvar , y=yvar)) +
  purrr::pmap(pars, function(a, b, row) {
    stat_function(aes(color = factor(row)), fun = function(x) x^a + 1 / x^b)  
  })

stefan
  • 90,330
  • 6
  • 25
  • 51