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

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

问题描述

我已经用 ggplot 创建了一个分面散点图,但我正在努力将回归线方程添加到每个方面.here 但这种方法不会扩展到分面图.

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?

推荐答案

这是一个从这个开始的例子 答案

Here is an example starting from this 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))

为两组创建方程标签

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 

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

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