r - 使用facet_wrap将r平方注释为ggplot

标签 r loops ggplot2 regression facet-wrap

我刚刚加入社区,期待为我的硕士论文的数据分析获得一些帮助。

目前我遇到以下问题:

我使用facet_wrap用ggplot绘制了42个品种:

`ggplot(sumfvvar,aes(x=TemperaturCmean,y=Fv.Fm,col=treatment))+
  geom_point(shape=1,size=1)+
  geom_smooth(method=lm)+
  scale_color_brewer(palette = "Set1")+
  facet_wrap(.~Variety)`

效果很好,但我想注释回归线的 r 平方值。我有两种处理方法和 42 个品种,因此有 84 条回归线。 是否有可能计算所有 r 平方值并将它们集成到 ggplot 中?我已经找到了该功能

ggplotRegression <- function (fit) {

require(ggplot2)

ggplot(fit$model, aes_string(x = names(fit$model)[2], y = names(fit$model)[1])) + 
geom_point() +
stat_smooth(method = "lm") +
labs(title = paste("Adj R2 = ",signif(summary(fit)$adj.r.squared, 5),
                   "Intercept =",signif(fit$coef[[1]],5 ),
                   " Slope =",signif(fit$coef[[2]], 5),
                   " P =",signif(summary(fit)$coef[2,4], 5)))
}

但这仅适用于一种品种和一种治疗方法。 lm() 函数的循环可能是一个选项吗?

最佳答案

这是一个使用 ggpmisc 包的示例:

library(ggpmisc)

set.seed(4321)
x <- 1:100
y <- (x + x^2 + x^3) + rnorm(length(x), mean = 0, sd = mean(x^3) / 4)
my.data <- data.frame(x = x, 
                      y = y,
                      group = c("A", "B"))
formula <- y ~ poly(x, 1, raw = TRUE)    
ggplot(my.data, aes(x, y)) + 
  facet_wrap(~ group) + 
  geom_point() +
  geom_smooth(method = "lm", formula = formula) +
  stat_poly_eq(formula = formula, parse = TRUE, 
               mapping = aes(label = stat(rr.label))) 

enter image description here

关于r - 使用facet_wrap将r平方注释为ggplot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58835392/

相关文章:

R 在 glue 语句中使用 bang-bang

r - ggplot2:如何交换 y 轴和右刻面带以及如何排序刻面值

javascript - 将数组连接到自身是否比遍历数组以创建更多索引更快?

c++ - for循环条件的性能差异?

r - 在ggplot中添加手动图例

r - 在 R 中提取一组短语后的单词/文本

r - Bookdown:是否可以在小节级别达到 "split_by"?

php - 在两个页面上显示 Wordpress 帖子

r - ggplot2:facet_wrap 基于数据集中变量的 strip 颜色

r - 将图例添加到 ggtree (ggplot) R