使用 facet_wrap 将 r 平方注释为 ggplot

annotate r squared to ggplot by using facet_wrap

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

目前我遇到以下问题:

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

`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() 函数的循环选项?

您不能将不同的标签应用于不同的方面,除非您向数据添加另一个 r^2 列。一种方法是使用 geom_text,但您需要先计算所需的统计信息.下面我展示了一个鸢尾花的例子,对于你的情况,只需将 Species 更改为 Variety,依此类推

library(tidyverse)
# simulate data for 2 treatments
# d2 is just shifted up from d1
d1 <- data.frame(iris,Treatment="A")
d2 <- data.frame(iris,Treatment="B") %>% 
mutate(Sepal.Length=Sepal.Length+rnorm(nrow(iris),1,0.5))
# combine datasets
DF <- rbind(d1,d2) %>% rename(Variety = Species)

# plot like you did
# note I use "free" scales, if scales very different between Species
# your facet plots will be squished
g <- ggplot(DF,aes(x=Sepal.Width,y=Sepal.Length,col=Treatment))+
  geom_point(shape=1,size=1)+
  geom_smooth(method=lm)+
  scale_color_brewer(palette = "Set1")+
  facet_wrap(.~Variety,scales="free")

# rsq function
RSQ = function(y,x){signif(summary(lm(y ~ x))$adj.r.squared, 3)}
#calculate rsq for variety + treatment
STATS <- DF %>%
group_by(Variety,Treatment) %>% 
summarise(Rsq=RSQ(Sepal.Length,Sepal.Width)) %>%
# make a label
# one other option is to use stringr::str_wrap in geom_text
mutate(Label=paste("Treat",Treatment,", Rsq=",Rsq))

# set vertical position of rsq
VJUST = ifelse(STATS$Treatment=="A",1.5,3)
# finally the plot function
g + geom_text(data=STATS,aes(x=-Inf,y=+Inf,label=Label),
hjust = -0.1, vjust = VJUST,size=3)

对于最后一个 geom_text() 调用,我通过乘以处理允许文本的 y 坐标不同。您可能需要根据您的情节进行调整..

下面是 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)))