如何将 stat_function 美学映射到 ggplot2 中的数据?

Gre*_*ory 5 r ggplot2

我想将一个stat_function图层添加到一个绘图中,其美学映射到某些标识一组参数的变量的状态。我在下面的最小工作示例中手动创建了两个 stat_function 行。这通常是结果的样子。

p <- ggplot(data.frame(x = -1:1), aes(x = x))
p + stat_function(fun = function (x) 0 + 1 * x, linetype = 'dotted') +
  stat_function(fun = function (x) 0.5 + -1 * x, linetype = 'solid')
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

我对如何做到这一点的最佳猜测是

params <- data.frame(
  type = c('true', 'estimate'),
  b = c(0, 0.5),
  m = c(1, -1),
  x = 0
)

linear_function <- function (x, b, m) b + m * x
p + stat_function(data = params,
                  aes(linetype = type, x = x),
                  fun = linear_function,
                  args = list(b = b, m = m))
Run Code Online (Sandbox Code Playgroud)

如果我使用诸如 之类的常量args = list(b = 0, m = 1),则此表单有效,但是当我尝试从 params 数据框中获取参数值时,它无法找到这些列。为什么这不像我期望的那样工作,有什么解决方案?

mer*_*erv 1

不幸的是,这里没有什么可以补充的;事实是:stat_function不支持此功能

另一种方法是使用 for 循环来制作图层,如本问题所示,或者自己生成网格数据,这是关于添加此功能的功能请求讨论的结束评论所建议的。