zl程序教程

您现在的位置是:首页 >  Java

当前栏目

R初学者必知图形添加显著性标记小细节

2023-02-18 16:35:33 时间

❝本节来介绍如何对图形做显著性标记,介绍两种方法第一种通过代码来自动进行标记,另一种通过手动的方式来添加标记;两种方法各有其独特的用处,各位观众老爷细细品味。

加载R包

library(tidyverse)
library(readxl)
library(ggsignif)
library(rstatix)
library(ggpubr)
library(ggsci)

统计分析

stat.test <- read_excel("41588_2022_1184_MOESM6_ESM.xlsx",sheet = 3) %>% 
  mutate(value=as.numeric(DTT)) %>% 
  drop_na() %>% 
  group_by(Loc) %>% 
  t_test(value ~ Type) %>%
  adjust_pvalue() %>% add_significance("p.adj") %>% 
  add_xy_position(x="Loc",scales="free",fun = "max")

添加显子性标记

read_excel("41588_2022_1184_MOESM6_ESM.xlsx",sheet = 3) %>% 
  mutate(value=as.numeric(DTT)) %>% 
  drop_na() %>% 
  ggplot(.,aes(Loc,value))+
  stat_summary(geom = "bar",position = "dodge",aes(fill=Type),width=0.4) +
  stat_pvalue_manual(stat.test,label = "p.adj.signif",label.size=5,hide.ns = T,
                     tip.length = 0.01)+
  stat_summary(geom = "errorbar",fun.data = "mean_sdl",
               fun.args = list(mult = 1),aes(fill=Type),
               position=position_dodge(0.4),width=0.2,color="black") +
  labs(x=NULL,y=NULL)+
  scale_fill_jama()+
  theme_test()+
  theme(legend.position = "top",
        legend.title = element_blank())

❝上述图形是通过代码自动判定了显著性的位置信息进而进行添加,如果数据分组较为复杂并且存在分面操作的情况;那么需要对上述代码的位置信息做过多的调整,因此第一种方法对初学者不太友好;接下来介绍如何使用「ggsignif」包来手动添加显著性标记 ❞

构建数据

dataf<- data.frame(Group<- c("G1","G1","G2","G2"),
                   Subject<- c("A","B","A","B"),
                   Score<- c(5,7,20,25))

案例一

ggplot(dataf, aes(Group,Score))+
  geom_bar(aes(fill = Subject), stat = "identity", 
           position = "dodge", width = .5)+
  geom_signif(y_position = c(10,26), xmin = c(0.8,1.8), 
              xmax = c(1.2,2.2), annotation = c("NS","**"),
              tip_length = 0)+
  geom_signif(comparisons = list(c("G1","G2")), y_position = 30,
              tip_length = 0, vjust = .1)+
  theme_light(base_size=10)

❝可以看到非常直观,简单明了但是此种方法只适用于数据量较小的情况 ❞

案例二

ggplot(dataf, aes(Group,Score))+
  geom_bar(aes(fill = Subject), stat = "identity", 
           position = "dodge", width = .5)+
  geom_signif(y_position = c(7.3,25.3), xmin = c(0.8,1.8), 
              xmax = c(1.2,2.2), annotation = c("Annotation","How i want it"),
              tip_length = 0)+
  geom_signif(comparisons = list(c("G1","G2")), y_position = 28,
              tip_length = 0, vjust = .1)+
  theme_light(base_size=13)

annotation参数还可以使用文本来进行注释

案例三

❝此外geom_signif还支持tip_length参数控制每一条竖线的的长度,的确很是贴心 ❞

ggplot(dataf, aes(Group,Score))+
  geom_bar(aes(fill = Subject), stat = "identity", 
           position = "dodge", width = .5)+
  geom_signif(y_position = c(7.3,25.3), xmin = c(0.8,1.8), 
              xmax = c(1.2,2.2), annotation = c("NS","**"),
              tip_length = 0.01)+
  geom_signif(comparisons = list(c("G1","G2")), y_position = 28,
              tip_length = c(1,0.1), vjust = .1)+
  theme_light(base_size=13)

本节介绍到此结束