美文网首页
R可视化:具有样本数目的Boxplot箱线图

R可视化:具有样本数目的Boxplot箱线图

作者: 生信学习者2 | 来源:发表于2021-08-18 22:09 被阅读0次

前言

boxplot是常用展示组间数据差异的方式,有时候会加入样本数目以及显著性标记。更多知识分享请到 https://zouhua.top/

Importing data

library(ggplot2)
library(dplyr)
library(tibble)
library(ggpubr)


dat <- iris %>% dplyr::select(Sepal.Length, Species) %>%
  mutate(Species=factor(Species))

group <- levels(dat$Species)

gg_color_hue <- function(n){
  hues <- seq(15,375,length=n+1)
  hcl(h=hues,l=65,c=100)[1:n]
}
cols <- gg_color_hue(length(group))

cmp <- NULL
for(i in 1:(length(group) -1 )){
  for(j in (i+1):length(group)){
    tmp <- c(group[i], group[j])
    if(is.null(cmp)){
      cmp[[1]] <- tmp
    }else{
      cmp[[i+1]] <- tmp
    }
  }
}

ggplot(dat, aes(x=Species, y=Sepal.Length, fill=Species))+
  stat_boxplot(geom = "errorbar", width = .12)+
  geom_boxplot(width = .3, outlier.shape = 3, outlier.size = 1)+
  stat_summary(fun = mean, geom = "point", shape = 16, 
               size = 2, color = "black") + 
  stat_summary(fun.data = function(x) {
    return(data.frame(y = 0.98 * ceiling(max(dat$Sepal.Length)), label = length(x)))
  }, geom = "text", hjust = 0.5, color = "red", size = 6)+
  guides(fill=F)+
  stat_compare_means(comparisons = cmp,
                     method = "wilcox.test", label = "p.label")+
  labs(x="",y="Sepal.Length")+
  theme_bw()+
  scale_fill_manual(values = cols)+
  scale_y_continuous(breaks = seq(ceiling(min(dat$Sepal.Length)), ceiling(max(dat$Sepal.Length)), 0.2),
                     limits = c(ceiling(min(dat$Sepal.Length))-1, ceiling(max(dat$Sepal.Length))+2),
                     expand = c(0, 0))+
  theme(plot.title = element_text(size = 10, color = "black", face = "bold", hjust = 0.5), 
        axis.title = element_text(size = 10, color = "black", face = "bold"),
        axis.text = element_text(size = 9, color = "black"),
        text = element_text(size = 8, color = "black"),
        strip.text = element_text(size = 9, color = "black", face = "bold"),
        panel.grid = element_blank(),
        legend.position = c(1, 0),
        legend.justification = c(1, 0),
        legend.background = element_rect(fill="white", color = "black"))

参考

参考文章如引起任何侵权问题,可以与我联系,谢谢。

相关文章

网友评论

      本文标题:R可视化:具有样本数目的Boxplot箱线图

      本文链接:https://www.haomeiwen.com/subject/djpnbltx.html