Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2: Plotting regression lines with different intercepts but with same slope

I want to plot regression lines with different intercepts but with the same slope.

With the following ggplot2 code, I can plot regression lines with different intercepts and different slopes. But could not figured out how to draw regression lines with different different intercepts but the same slopes.

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
like image 904
MYaseen208 Avatar asked Aug 09 '15 11:08

MYaseen208


1 Answers

Why don't you calculate the regression outside of ggplot with the results from 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))

Produces same slope and different intercepts: enter image description here

Technically as you see in your model there is not two different intercepts but an extra offset to the dummy variable GenderFemale.

Edit: included predict to simplify, thanks to @aosmith for suggesting.

like image 172
mts Avatar answered Oct 30 '22 09:10

mts