ggplot:使用Facet添加回归线方程和R2

时间:2013-10-31 06:34:54

标签: r ggplot2

我用ggplot创建了一个多面散点图,但我很难将回归线方程添加到每个方面。没有刻面的简单情况已被回答here,但这种方法不会扩展到刻面图。

如何以干净的方式实现这一目标?

3 个答案:

答案 0 :(得分:24)

以下是从此answer

开始的示例
require(ggplot2)
require(plyr)

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


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));                 
}

创建两个要进行分组的组

df$group <- c(rep(1:2,50))

为两组创建方程式标签

eq <- ddply(df,.(group),lm_eqn)

并绘制

p <- ggplot(data = df, aes(x = x, y = y)) +
            geom_smooth(method = "lm", se=FALSE, color="black", formula = y ~ x) +
            geom_point()
p1 = p + geom_text(data=eq,aes(x = 25, y = 300,label=V1), parse = TRUE, inherit.aes=FALSE) + facet_grid(group~.)
p1 

enter image description here

答案 1 :(得分:5)

这样做你想要的吗?

library(ggplot2); library(gridExtra)
ggplot(iris, aes(Sepal.Length, Sepal.Width)) +
  geom_point() +
  geom_smooth(method="lm") +
  facet_wrap(~ Species)

grid.newpage()
vpa_ <- viewport(width = 1, height = 1)
print(p, vp = vpa_)
grid.text("y ~ mx + b", x=0.3, y=0.8)
grid.text("y ~ mx + b", x=0.5, y=0.8)
grid.text("y ~ mx + b", x=0.8, y=0.8)

enter image description here

答案 2 :(得分:4)

使用gridExtra你可以安排你的情节。

enter image description here

library(ggplot2)

library(ggplot2)
iris$x = iris$Sepal.Length 
iris$y = iris$Sepal.Width
xx <- range(iris$x)
yy <- range(iris$y)

ll <- by(iris,iris$Species,function(df){
  x.eq <- max(xx)-mean(xx)/2
  y.eq <- max(yy)*0.95
  p <- ggplot(df, aes(x, y)) +
    geom_point() +
    geom_smooth(method="lm") +
    annotate(x=x.eq, y =y.eq ,  geom='text',
              label = lm_eqn(df), size=5,parse=TRUE) +
    xlim(xx[1],xx[2])+ylim(yy[1],yy[2])
})

library(gridExtra)
do.call(grid.arrange,ll)