简体   繁体   中英

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

Using the mtcars dataset as an example, I am using this code.

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)

I would like to add the sample size to each facet, so that it says "n = " sample size. I tried the following modification, but no luck. Might anyone have any suggestions on how to fix this, please?

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))

Suggestion to make things a little easier: create a new column for cylinder + sample size and use that for the facet titles.

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)

Result:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM