5

I would like to create a ggplot2 plot by faceting geom_function, so that a parameter of the function varies across the grid. e.g. something like this:

my_function<-function(x, par)
{
 if(par==1)
 {
  return(sin(x))
 }
 else
 {
  return(cos(x))
 }
}

> head(data)
      x parameter
1 -1.00   1
2 -0.99   1
3 -0.98   1
4 -0.97   1
5 -0.96   1
6 -0.95   1

> tail(data)
       x parameter
397 0.95   2
398 0.96   2
399 0.97   2
400 0.98   2
401 0.99   2
402 1.00   2

> my_plot<-ggplot(data, aes(x)) + geom_function(fun = my_function, args=list(par=parameter)+facet_wrap(~parameter)

which doesn't work because "parameter" is not in scope for the args parameter of geom_function. Is this possible?

Z.Lin
  • 28,055
  • 6
  • 54
  • 94
wjastle
  • 157
  • 1
  • 7

1 Answers1

7

I don't think it is possible to map function arguments to facets, at least not with geom_function(). The reason I think this is that the geom is practically blind to anything going on with the data, and the function itself only ever sees a sequence along the x-axis (and the args argument). However, I would suggest the following workaround, where you make geom_function() for facets individually by setting the facetting column for that layer. Example below:

library(ggplot2)

set.seed(0)
df <- data.frame(
  x = 1:10,
  y = 1:10 / 10,
  z = sample(LETTERS[1:2], 10, replace = TRUE)
)

ggplot(df) +
  geom_point(aes(x, y)) +
  geom_function(data = transform(df, z = "A"),
                fun = dnorm, args = list(mean = 2.5, sd = 1)) +
  geom_function(data = transform(df, z = "B"),
                fun = dnorm, args = list(mean = 7.5, sd = 2)) +
  facet_wrap(~ z)

Created on 2020-09-17 by the reprex package (v0.3.0)

teunbrand
  • 33,645
  • 4
  • 37
  • 63