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

时间:2016-08-17 00:32:49

标签: 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')

enter image description here

我最好的猜测是如何实现这一目标

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

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

1 个答案:

答案 0 :(得分:0)

不幸的是,这里没有任何积极的补充;事实是: stat_function不支持此功能

另一种选择是使用this question中所示的for循环来制作图层,或者自己生成网格数据,这是对a feature request discussion about adding this functionality的总结。