Home > database >  ggplot using stat_function in a loop
ggplot using stat_function in a loop

Time:01-04

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?

CodePudding user response:

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)  
  })

  • Related