【问题标题】:Ggplot: 1 Regression line with constant and 1 withoutGgplot:1条回归线有常数,1条没有
【发布时间】:2018-10-07 23:48:40
【问题描述】:

对于大学练习,我想在同一张图中绘制两条回归线:一条回归包含常数,另一条不包含。它应该说明移除常数如何改变回归线。

但是,当我使用以下 ggplot 命令时,我只得到一条回归线。有人知道这是什么原因以及如何解决吗?

data(mtcars)
ggplot(mtcars, aes(x=disp, y=mpg)) +
  geom_point() +    # Scatters
  geom_smooth(method=lm, se=FALSE)+
  geom_smooth(method=lm, aes(color='red'),
              formula = y ~ x -0, #remove constant
              se=FALSE)

我试过this,但没有成功。

【问题讨论】:

  • 你已经得到了下面的答案,但作为一个旁注:color = 'red' 不需要在 aes() 内为你的第二个 geom_smooth 层。
  • 啊完美,这真的让我很烦。谢谢!

标签: r ggplot2


【解决方案1】:

你几乎明白了;要删除拦截,您需要+ 0- 1,但不需要- 0;来自help("lm")

公式具有隐含的截距项。要删除此使用 y ~ x - 1 或 y ~ 0 + x。有关允许的公式的更多详细信息,请参见公式。

所以,我们可以这样做:

library(ggplot2)

data(mtcars)
ggplot(mtcars, aes(x=disp, y=mpg)) +
    geom_point() +    # Scatters
    geom_smooth(method=lm, se=FALSE)+
    geom_smooth(method=lm, aes(color='red'),
                formula = y ~ x - 1, #remove constant
                se=FALSE)

reprex package (v0.2.1) 于 2018 年 10 月 7 日创建

【讨论】:

  • 完美,成功了!非常感谢,也感谢您的快速回答。
【解决方案2】:

美好的一天,

好书说要这样做: http://bighow.org/questions/18280770/formatting-regression-line-equation-using-ggplot2-in-r 我不能将代码编写归功于研究...

祝你有美好的一天... 卡布利特

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-03
    • 1970-01-01
    • 1970-01-01
    • 2019-10-20
    • 1970-01-01
    • 1970-01-01
    • 2012-06-02
    • 2017-11-05
    相关资源
    最近更新 更多