ggplot2 geom_function 可以跨 arg 值进行分面吗?

wja*_*tle 6 r ggplot2

我想通过分面 geom_function 创建 ggplot2 图,以便函数的参数在网格中变化。例如这样的东西:

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)
Run Code Online (Sandbox Code Playgroud)

这不起作用,因为“参数”不在 geom_function 的 args 参数范围内。这可能吗?

teu*_*and 10

我认为不可能将函数参数映射到构面,至少不能使用geom_function(). 我认为这是因为 geom 实际上对数据发生的任何事情都视而不见,并且函数本身只能看到沿 x 轴(和参数args)的序列。但是,我建议使用以下解决方法,geom_function()通过设置该层的分面列来单独制作分面。下面的例子:

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)
Run Code Online (Sandbox Code Playgroud)

由reprex 包(v0.3.0)于 2020-09-17 创建