2011-11-29 51 views

回答

6

不是很快,但可能的:

首先,拟合模型与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) 

enter image description here

5

Ramnath's回答类似的问题,我问较早前。

library(ggplot2) 
df <- data.frame(x = c(1:100)) 
df$y <- 2 + 3 * df$x + rnorm(100, sd = 40) 

# GET EQUATION AND R-SQUARED AS STRING 
# SOURCE: http://goo.gl/K4yh 

lm_eqn = function(df){ 
    m = lm(y ~ x, df); 
    eq <- substitute(italic(y) == a + b %.% italic(x)*","~~italic(r)^2~"="~r2, 
     list(a = format(coef(m)[1], digits = 2), 
       b = format(coef(m)[2], digits = 2), 
      r2 = format(summary(m)$r.squared, digits = 3))) 
    as.character(as.expression(eq));     
} 

p <- ggplot(data = df, aes(x = x, y = y)) + 
      geom_smooth(method = "lm", se=FALSE, color="black", formula = y ~ x) + 
      geom_point() 

p <- p + geom_text(aes(x = 25, y = 300, label = lm_eqn(df)), parse = TRUE) 
print(p) 

Output