ggplot的“快速”散点图传奇?

时间:2011-11-29 15:47:03

标签: r ggplot2

  

可能重复:
  ggplot2: Adding Regression Line Equation and R2 on graph

我用

绘制散点图中的数据
ggplot(work.rootsfnp.h1, aes(x=fnpltrfac, y=rootsscore, group=1)) + 
  geom_smooth(method=lm, se = F) + geom_point(shape=1)

是否有“快速”方式添加基本图例,其中包括最佳拟合线的公式以及相关系数?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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