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

Hyd*_*dro 5 r scatter-plot linear-regression ggplot2 facet-grid

有没有办法来改变首先从属性标签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()
Run Code Online (Sandbox Code Playgroud)

这是我使用上述代码得到的图。 在此处输入图片说明 我尝试了下面的代码来更改 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()
Run Code Online (Sandbox Code Playgroud)

我不知道如何添加R2facets. 是否有计算和任何有效的方式R2facets

H 1*_*H 1 8

您可以使用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")
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

  • 使用 stat_cor(aes(label = Paste(..rr.label.., ..p.label.., sep = "~")), color = "red", geom = "label")` (2认同)

www*_*www 5

如果您不想使用其他包中的函数而只​​想使用ggplot2,则需要计算R2每个SUB和 的Variable组合,然后使用geom_text或添加到绘图中geom_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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述