不是很快,但可能的:
首先,擬合模型與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)