[英]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)
結果:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.