ggplot:使用分面添加回归直线方程和R2 [英] ggplot: Adding Regression Line Equation and R2 with Facet

查看:545
本文介绍了ggplot:使用分面添加回归直线方程和R2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经用 ggplot 创建了一个分面散点图,但我很努力地将回归直线方程添加到每个方面。没有分面的简单情况已被回答这里< a>但这种方法不会延伸到一个方面的情节。

I've created a faceted scatterplot with ggplot but I'm struggling to add the regression line equation to each of the facets. The simple case where there is no faceting has been answered here but this method won't extend to a faceted plot.

任何想法如何以干净的方式完成这个?

Any ideas how to accomplish this in a clean fashion?

推荐答案

这是一个从 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));                 
}

创建两个你想要面向的组

Create two groups on which you want to facet

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

为两组创建方程标签

Create the equation labels for the two groups

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

以及

And plot

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 

这篇关于ggplot:使用分面添加回归直线方程和R2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆