将样本大小 (n) 添加到每个方面散点图 (R, ggpubr)

Add sample size (n) to each facet scatter plot (R, ggpubr)

以mtcars数据集为例,我使用的是这段代码

library(ggplot2)
library(ggpubr)
ggscatter(mtcars, x = "qsec", y = "disp", facet.by = "cyl", add = "reg.line", add.params = list(color = "blue", fill = "lightblue"), conf.int = TRUE, cor.method = "spearman", cor.coef = TRUE)

我想将样本大小添加到每个方面,以便显示 "n = " 样本大小。我尝试了以下修改,但没有运气。请问有人对如何解决这个问题有什么建议吗?

library(ggplot2)
library(ggpubr)
give.n <- function(x){return(c(y = min(mtcars$disp), label = length(x)))}
ggscatter(mtcars, x = "qsec", y = "disp", facet.by = "cyl", add = "reg.line", add.params = list(color = "blue", fill = "lightblue"), conf.int = TRUE, cor.method = "spearman", cor.coef = TRUE) + geom_text(paste0("n = ", (data = give.n, aes(cyl, disp, label = n), vjust = 2))

让事情变得更简单的建议:为柱面 + 样本大小创建一个新列,并将其用于分面标题。

library(ggpubr)
library(dplyr)

mtcars %>% 
  group_by(cyl) %>% 
  mutate(n = paste0("cyl = ", cyl, ", n = ", n())) %>% 
  ggscatter(., x = "qsec", y = "disp", facet.by = "n", add = "reg.line", 
            add.params = list(color = "blue", fill = "lightblue"), conf.int = TRUE, 
            cor.method = "spearman", cor.coef = TRUE)

结果: