使用分面添加回归直线方程和R2

使用分面添加回归直线方程和R2

本文介绍了ggplot:使用分面添加回归直线方程和R2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我已经用 ggplot 创建了一个分面散点图,但我很努力地将回归直线方程添加到每个方面。没有分面的简单情况已被回答这里但这种方法不会延伸到一个方面的情节。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?推荐答案这是一个从 answerrequire(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 facetdf$group <- c(rep(1:2,50))为两组创建方程标签Create the equation labels for the two groupseq <- ddply(df,.(group),lm_eqn)以及And plotp <- 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
07-29 12:29