2015-08-09 179 views
2

我想绘制回归线与不同的拦截,但具有相同的斜率。GGPLOT2:绘制回归线与不同的拦截,但与相同的斜率

用下面ggplot2代码,我可以绘制回归曲线与不同截距和不同的斜率。但无法弄清楚如何绘制具有不同截距但不同斜率的回归线。任何帮助将不胜感激。由于

library(ggplot2) 
    ggplot(data=df3, mapping=aes(x=Income, y=Consumption, color=Gender)) + geom_point() + 
    geom_smooth(data=df3, method = "lm", se=FALSE, mapping=aes(x=Income, y=Consumption)) 

Consumption <- c(51, 52, 53, 54, 56, 57, 55, 56, 58, 59, 62, 63) 
Gender <- gl(n = 2, k = 6, length = 2*6, labels = c("Male", "Female"), ordered = FALSE) 
Income <- rep(x=c(80, 90, 100), each=2) 
df3 <- data.frame(Consumption, Gender, Income) 
df3 

# Regression with same slope but different intercepts for each Gender 
fm1 <- lm(formula=Consumption~Gender+Income, data=df3) 
summary(fm1) 

Call: 
lm(formula = Consumption ~ Gender + Income, data = df3) 

Residuals: 
    Min  1Q Median  3Q  Max 
-0.8333 -0.8333 0.1667 0.1667 1.1667 

Coefficients: 
      Estimate Std. Error t value Pr(>|t|)  
(Intercept) 26.83333 2.54557 10.54 2.30e-06 *** 
GenderFemale 5.00000 0.45812 10.91 1.72e-06 *** 
Income  0.30000 0.02805 10.69 2.04e-06 *** 
--- 
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 

Residual standard error: 0.7935 on 9 degrees of freedom 
Multiple R-squared: 0.9629, Adjusted R-squared: 0.9546 
F-statistic: 116.7 on 2 and 9 DF, p-value: 3.657e-07 
+0

你为什么不添加一个'geom_line'与'lm',即结果呢ggplot外的计算?从技术上讲,你在你的模型中看到没有两种不同的拦截,但额外的偏移来假'GenderFemale' – mts

+0

可能是一个统计问题。你的ggplot代码通过使用color = Gender来做什么是为每个性别创建一个线性回归模型。因此,该模型将确定它们是否具有相同的斜率和/或相同的截距。如果它实际上具有相同的斜率和不同的截距,请确保它将被绘制。你为什么要强迫男女同性恋? – AntoniosK

回答

2

你为什么不计算回归的结果ggplot之外从lm

# Regression with same slope but different intercepts for each Gender 
fm1 <- lm(formula=Consumption~Gender+Income, data=df3) 
df3 = cbind(df3, pred = predict(fm1)) 

ggplot(data=df3, mapping=aes(x=Income, y=Consumption, color=Gender)) + geom_point() + 
    geom_line(mapping=aes(y=pred)) 

主要生产相同的斜率和截距不同: enter image description here

从技术上讲,你在看您的模型没有两个不同的截距,但是对虚拟变量GenderFemale有额外的偏移量。

编辑:包括predict简化,这要归功于@aosmith用于建议。

+2

您可以通过使用'lm1'对象的'predict'来简化这一点,或者使用新的数据集[如此处所示](https://stat.ethz.ch/pipermail/r-help/2012-December/ 343458.html),或者通过直接将预测添加到原始数据集进行绘图[如在此答案中](http://stackoverflow.com/a/1477938/2461552) – aosmith

+0

@aosmith,感谢您指出这一点,事实上要好得多! – mts

+0

上例中运行'fm1s < - summary(fm1)'的实用程序是什么? – bpace