【问题标题】:slope and intercept issue in scatterplot ggplot2散点图ggplot2中的斜率和截距问题
【发布时间】:2013-03-03 00:03:50
【问题描述】:

我正在使用 mtcars 数据集 (mpg ~ cyl) 绘制回归线(线性)。我使用mpg 和cyl 运行了一个简单的线性模型并执行了总结。

线性模型摘要中的截距与图形表示不匹配。

我很难理解发生了什么。如果我使用 R 的基础绘图功能来绘制散点图,我会得到与 ggplot2 相同的结果。我更改了 y 轴刻度限制 (0, 40) 没有任何成功。

这是我的代码

data(mtcars)
library(ggplot2)
p <- ggplot(mtcars, aes(x=cyl, y=mpg)) + geom_point(shape=1) # create graph
p + geom_smooth(method = lm, se=FALSE) # add line
lm.car <- lm(mpg ~ cyl) # create linear model
summary(lm.car) # summary

这是线性模型输出

> summary(lm.car)

Call:
lm(formula = mpg ~ cyl)

Residuals:
    Min      1Q  Median      3Q     Max 
-4.9814 -2.1185  0.2217  1.0717  7.5186 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept)  37.8846     2.0738   18.27  < 2e-16

cyl          -2.8758     0.3224   -8.92 6.11e-10 

Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 

Residual standard error: 3.206 on 30 degrees of freedom
Multiple R-squared: 0.7262, Adjusted R-squared: 0.7171 
F-statistic: 79.56 on 1 and 30 DF,  p-value: 6.113e-10 

根据我使用的以下建议

data(mtcars)
library(ggplot2)
p <- ggplot(mtcars, aes(x=cyl, y=mpg)) + geom_point(shape=1) +
    xlim(0, 10)# create graph
p + geom_smooth(method = lm, se=FALSE) # add line

这是输出:

【问题讨论】:

  • @Julius:感谢格式化帮助。

标签: r ggplot2 lm


【解决方案1】:

当您进行回归分析时,Intercept 值显示如果x 值为 0,y 值将有多大。在cyl 和mpgIntercept 值的情况下,Intercept 值 37.8846 表示mpg如果cyl 的值为 O,则为 37.8846。

在ggplot2 绘图回归线上仅显示从 4 到 6 的 cyl 值(因为没有其他值)。

如果您计算mpg 的预测值cyl 值4,您将得到 26.38142。这就是你在情节上看到的价值。

predict(lm.car,data.frame(cyl=4))
       1 
26.38142 

【讨论】:

  • 感谢您的解释。它有助于理解问题的本质。根据您的解释,我认为我应该使用xlim(0, 10)。这解决了这个问题。再次感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-03
相关资源
最近更新 更多