Hi,
In ggplot2 using the ToothGrowth data from R, I've been trying to fit the following models where the factor w has been introduced:
lm(y ~ w) : yhat = B0 + B2 * w
lm(y ~ x + w) : yhat = B0 + B1 * x + B2 * w
lm(y ~ x * w) : yhat = B0 + B1 * x + B2 * w + B3 * x * w
I've tried using the formula option in geom_smooth() but my ggplot2 code doesn't recognize the factor supp.
ggplot(data = ToothGrowth, aes(x = dose, y = len, color = supp)) + geom_point(pch = 19, size = 2, alpha = 0.4) + xlab('Dose') + ylab('Length') + theme_bw() + scale_color_manual(name = 'Supplements', breaks = c('OJ', 'VC'), values = c('red', 'blue')) + geom_smooth(method = 'lm', formula = (y ~ x * supp)) + ggtitle('y = B0 + B1 * x + B2 * w + B3 * x * w')
As a matter of fact, I get the error message:
Warning message: Computation failed in `stat_smooth()`: object 'supp' not found.
I was thinking of using this workaround using geom_abline with first lm, but it doesn't give me the error bands.
fit <- lm(data = ToothGrowth, len ~ dose * supp)
ggplot(data = ToothGrowth, aes(x = dose, y = len, color = supp)) + geom_point(pch = 19, size = 2, alpha = 0.4) + xlab('Dose') + ylab('Length') + theme_bw() + scale_color_manual(name = 'Supplements', breaks = c('OJ', 'VC'), labels = c('Orange Juice', 'Vitamin C'), values = c('red', 'blue')) + ggtitle('y = B0 + B1 * x + B2 * w + B3 * x * w') + geom_abline(intercept = coef(fit)[1], slope = coef(fit)[2], col = 'red', lwd = 1) + geom_abline(intercept = coef(fit)[1] + coef(fit)[3], slope = coef(fit)[2] + coef(fit)[4], col = 'blue', lwd = 1)
Any suggestions?
Angelo