使用Mtcars示例获得散点图中最佳拟合线

时间:2018-04-26 08:23:44

标签: r

您好,您如何获得Weight vs Milage散点图的最佳拟合线?即使他们有点分散。以下是我的代码:

plot(x = mtcars$wt,y = mtcars$mpg,
     xlab = "Weight",
     ylab = "Milage",
     xlim = c(2.5,5),
     ylim = c(15,30),        
     main = "Weight vs Milage")

enter image description here

2 个答案:

答案 0 :(得分:2)

由于您正在使用基地R plot,您可以这样做:

plot(x = mtcars$wt,y = mtcars$mpg,
 xlab = "Weight",
 ylab = "Milage",
 xlim = c(2.5,5),
 ylim = c(15,30),        
 main = "Weight vs Milage")
abline(lm(mpg ~ wt, data = mtcars), col = "red")

enter image description here

说明:lm(mpg ~ wt, data = mtcars)在一个简单的线性模型中对mpg上的wt进行了回归; abline可以将lm返回对象作为输入来绘制回归线。

答案 1 :(得分:0)

library(ggplot2)

ggplot(mtcars, aes(x = wt, y = mpg)) + 
  geom_point() +
  stat_smooth(method = "lm", col = "red", se = F)