【问题标题】:Graph function from multiple coefficient estimates with ggplot in R使用 R 中的 ggplot 来自多个系数估计的图形函数
【发布时间】:2026-01-28 12:00:01
【问题描述】:

我正在尝试在 ggplot 中的同一数字上绘制回归估计中的隐含函数。在下面的示例中,我创建了一个简单的线性函数,其中 c 和 b 是从早期回归中存储的系数估计值。然后我试图按组在 [0,50] 范围内绘制函数(最好也使用选项:color = groups)。

library(ggplot2)

groups = c("a", "b", "c")
c = c(5, 4, 3)
b = c(-0.01, -0.002, -0.001)
x = c(0, 0, 0)
df <- data.frame(cbind(c, b, x))

grad_fun <- function(x) {
  c + b*x
}

ggplot(data = df, aes(x = x, group = groups)) +
  stat_function(fun = grad_fun) + 
  xlim(0, 50)

我的身材是这样的,但我似乎无法找出原因。欢迎任何有关如何解决此问题的建议。 Image: Outcome of above code

【问题讨论】:

    标签: r function ggplot2


    【解决方案1】:

    有几点:

    • geom_abline 不是使用自定义函数,而是您的朋友。
    • 请注意,group = group 在这种情况下不会做任何事情——您需要指定组的显示方式,所以它应该是color = group
    • 最后,在不必要的地方使用 cbind 时要小心 - 它会将您的数字参数转换为因子,然后无法绘制。

    下面的代码应该做你想做的:

    library(ggplot2)
    
    groups = c("a", "b", "c")
    c = c(5, 4, 3)
    b = c(-0.01, -0.002, -0.001)
    df <- data.frame(c, b, groups)
    
    ggplot(data = df) +
      geom_abline(aes(slope = b, intercept = c, color = groups)) +
      xlim(0,50) + ylim(0,5)
    

    geom_abline 仅适用于 y = m*x + b 形式的仿射函数。相反,如果您想使用任何函数,则需要使用 stat_function 并将它们添加到如下所示的循环中。您还可以为数据添加颜色

    library(ggplot2)
    
    groups = c("a", "b", "c")
    a = c(-1, 3, 2)
    c = c(5, 4, 3)
    b = c(-0.01, -0.002, -0.001)
    colors = RColorBrewer::brewer.pal(length(a), "Dark2")
    df <- data.frame(a, b, c, groups, x = 0, colors)
    
    fun <- function(x, a, b, c){
      function(x) a*x^2 + b*x + c 
    }
    
    funs <- mapply(fun, a = df$a, b = df$b, c = df$c)
    
    p <- ggplot(data = df, aes(x=x)) +
      xlim(-50,50) 
    
    for (i in seq_len(nrow(df))){
      p <- p +
        stat_function(fun = funs[[i]], color = colors[i])
    }
    
    print(p)
    

    【讨论】:

    • 这太好了,谢谢!如果我想包含一个多项式项,即 c + bx + bx^2 或对数函数形式,即 ln(y) = c + b*ln(x),该怎么办? geom_abline 可以处理吗?
    • 非常感谢@Alex,这正是我想要的!