如何在 R 中为 ggplot 的每个方面添加 R2?

How to add R2 for each facet of ggplot in R?

有没有办法先将 facet 标签从 1:3 更改为 c(good, bad, ugly) 之类的东西。另外,我想为每个方面添加 R2 值。下面是我的代码——我尝试了一些但没有成功。

DF = data.frame(SUB = rep(1:3, each = 100), Ob = runif(300, 50,100), S1 = runif(300, 75,95), S2 = runif(300, 40,90),
                S3 = runif(300, 35,80),S4 = runif(300, 55,100))
FakeData = gather(DF, key = "Variable", value = "Value", -c(SUB,Ob))

ggplot(FakeData, aes(x = Ob, y = Value))+
  geom_point()+ geom_smooth(method="lm") + facet_grid(Variable ~ SUB,  scales = "free_y")+
  theme_bw()

这是我使用上面的代码得到的图。 我尝试了下面的代码来更改 facet_label 但它没有用

ggplot(FakeData, SUB = factor(SUB, levels = c("Good", "Bad","Ugly")), aes(x = Ob, y = Value))+
  geom_point()+ geom_smooth(method="lm") + facet_grid(Variable ~ SUB,  scales = "free_y")+
  theme_bw()

我不知道如何将 R2 添加到 facetsR2facets 有什么有效的计算方法吗?

您可以使用 ggpubr::stat_cor() 轻松地将相关系数添加到您的图中。

library(dplyr)
library(ggplot2)
library(ggpubr)

FakeData %>%
  mutate(SUB = factor(SUB, labels = c("good", "bad", "ugly"))) %>%
  ggplot(aes(x = Ob, y = Value)) +
  geom_point() +
  geom_smooth(method = "lm") +
  facet_grid(Variable ~ SUB,  scales = "free_y") +
  theme_bw() +
  stat_cor(aes(label = ..rr.label..), color = "red", geom = "label")

如果您不想使用其他包中的函数而只​​想使用 ggplot2,您将需要为每个 SUB 和 [=14] 计算 R2 =] 组合,然后使用 geom_textgeom_label 添加到您的绘图中。这是一种方法。

library(tidyverse)

set.seed(1)

DF = data.frame(SUB = rep(1:3, each = 100), Ob = runif(300, 50,100), S1 = runif(300, 75,95), S2 = runif(300, 40,90),
                S3 = runif(300, 35,80),S4 = runif(300, 55,100))
FakeData = gather(DF, key = "Variable", value = "Value", -c(SUB,Ob))

FakeData_lm <- FakeData %>%
  group_by(SUB, Variable) %>%
  nest() %>%
  # Fit linear model
  mutate(Mod = map(data, ~lm(Value ~ Ob, data = .x))) %>%
  # Get the R2
  mutate(R2 = map_dbl(Mod, ~round(summary(.x)$r.squared, 3))) 

ggplot(FakeData, aes(x = Ob, y = Value))+
  geom_point()+ 
  geom_smooth(method="lm") + 
  # Add label
  geom_label(data = FakeData_lm, 
             aes(x = Inf, y = Inf, 
                 label = paste("R2 = ", R2, sep = " ")),
             hjust = 1, vjust = 1) +
  facet_grid(Variable ~ SUB,  scales = "free_y") +
  theme_bw()