【问题标题】:How to get `geom_smooth()` to understand the formula in result of `lm()`?如何让 `geom_smooth()` 理解 `lm()` 结果中的公式?
【发布时间】:2018-08-04 08:49:21
【问题描述】:

我想使用geom_smooth() 显示任意拟合函数。

我已经生成了一个线性回归模型: fit <- lm(loss ~ hardness + strength, data = rubber)

我想在调用图中使用这个模型:

ggplot(fit$model, aes_string(x = names(fit$model)[2], y = names(fit$model)[1])) + 
    geom_point() +
    geom_smooth(method = "lm", 
                formula = ????? something to do with *fit*, 
                col = "red")

使用formula参数引用fit中使用的公式。

我可以查看通过评估fit$terms 使用的公式,但是如何将其传递给geom_smooth()

我看到的所有示例都有明确写出的公式,但我想将此调用包装在一个函数中以用于任意模型。

我尝试过传入fit$termsstr(fit$terms)deparse(fit$terms)do.call(fit$terms),以及主题的各种变体。

【问题讨论】:

  • deparse(fit$call)?
  • 不! “stat_smooth() 中的计算失败:未找到对象 'loss'” 但不错的尝试。
  • 我不确定这种方法...但是如果没有公式,它也可以正常工作-如果您只是删除该行-因为 geom_smooth 期待来自 aes 的 2 个参数
  • @Stephen,非常正确,但没有指定公式,似乎geom_smooth() 仅使用绘制的两个变量重新计算模型。我希望它使用具有更多变量的模型。

标签: r ggplot2 expression call lm


【解决方案1】:

看起来像

formula = str(fit$call)

做我想做的事。

感谢 jaySf 的指点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-09-29
    • 1970-01-01
    • 2018-10-15
    • 2019-08-21
    • 2021-05-27
    • 2017-03-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多