是否可以先将构面标签从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
添加到facets
。有没有有效的计算方法,并且R2
到facets
?
您可以使用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
,则需要为每个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()