不是很快,但可能的:
首先,拟合模型与lm
model <- lm(mpg ~ wt + factor(cyl), data=mtcars)
然后提取系数和R^2,构建表达为每个
x <- coef(model)
intercept <- signif(x[1], 3)
terms <- paste(signif(x[-1], 3), names(x[-1]), sep="*", collapse= " + ")
e1 <- paste(intercept, terms, collapse = " + ")
e2 <- paste("R^2 = ", round(summary(model)$r.squared, 3))
最后,与ggplot
一起绘制并使用annotate
放置标签。
ggplot(mtcars, aes(x=wt, y=mpg)) +
geom_point() +
geom_smooth(method=lm) +
annotate("text", label=e1, x=max(mtcars$wt), y=max(mtcars$mpg),
hjust=1, size=3, vjust=0) +
annotate("text", label=e2, x=max(mtcars$wt), y=max(mtcars$mpg),
hjust=1, size=3, vjust=1)