顯著性標(biāo)記箱線散點(diǎn)圖
本篇筆記的內(nèi)容是在R語言中利用ggplot2,ggsignif,ggsci,ggpubr等包制作箱線散點(diǎn)圖,并計(jì)算指定變量之間的顯著性水平,對(duì)不同分組進(jìn)行特異性標(biāo)記,最終效果如下。

加載R包
library(ggplot2)
library(ggsignif)
library(ggsci)
library(ggpubr)
載入示例數(shù)據(jù)
本次使用R語言自帶的數(shù)據(jù)集mpg進(jìn)行演示,內(nèi)含不同汽車的相關(guān)數(shù)據(jù)指標(biāo)。
df <- mpg
head(mpg)

進(jìn)行繪圖
ggplot(df,aes(class,hwy))+
geom_boxplot(aes(fill=class))

首先繪制出一張普通的箱線圖,填充顏色與車型分類class變量有關(guān),然后在其基礎(chǔ)上添加圖層。下面檢測(cè)compact\~pickup和subcompact\~suv的相關(guān)性,采用t測(cè)驗(yàn),標(biāo)注信息與橫線距離0.1,兩端豎線距離0.05
ggplot(df,aes(class,hwy))+
geom_boxplot(aes(fill=class))+
geom_signif(
comparisons = list(
c("compact","pickup"),
c("subcompact","suv")
), #檢測(cè)兩者之間的差異顯著性
map_signif_level = T, #添加星號(hào)標(biāo)記
test = "t.test", #檢測(cè)方法
vjust=0.1, #標(biāo)注和橫線的距離
tip_length = 0.05 #兩端短豎線的長(zhǎng)度
)

現(xiàn)在可以從圖中看出顯著性檢驗(yàn)的結(jié)果,如果想顯示p值,只需要將map_signif_level改為F即可,接下來對(duì)圖片添加注釋信息。
ggplot(df,aes(class,hwy))+
geom_boxplot(aes(fill=class))+
geom_signif(
comparisons = list(
c("compact","pickup"),
c("subcompact","suv")
), #檢測(cè)兩者之間的差異顯著性
map_signif_level = T, #添加星號(hào)標(biāo)記
test = "t.test", #檢測(cè)方法
vjust=0.1, #標(biāo)注和橫線的距離
tip_length = 0.05 #兩端短豎線的長(zhǎng)度
)+
geom_signif(
annotations = c("one","two"), #添加注釋
y_position = c(40,42),xmin = c(2,1),xmax = c(5,3) #添加的位置
)

添加位置信息使用annotations參數(shù),設(shè)置信息后利用位置參數(shù)進(jìn)行標(biāo)注。添加散點(diǎn)圖的圖層,設(shè)置點(diǎn)的顏色和位置,更改箱線圖的透明度為70%,最后,再對(duì)結(jié)果進(jìn)行主題修改和美化,最終呈現(xiàn)如下效果:
ggplot(df,aes(class,hwy))+
geom_point(aes(color = class),position = "jitter")+
geom_boxplot(aes(fill=class),alpha=0.7)+
geom_signif(
comparisons = list(
c("compact","pickup"),
c("subcompact","suv")
), #檢測(cè)兩者之間的差異顯著性
map_signif_level = T, #添加星號(hào)標(biāo)記
test = "t.test", #檢測(cè)方法
vjust=0.1, #標(biāo)注和橫線的距離
tip_length = 0.05 #兩端短豎線的長(zhǎng)度
)+
geom_signif(
annotations = c("one","two"), #添加注釋
y_position = c(40,42),xmin = c(2,2),xmax = c(5,3) #添加的位置
)+
scale_y_continuous(limits = c(10,48))+
theme_bw()+
theme(
legend.position = "none",
axis.title = element_text(size = 15,face = "bold"),
axis.text.x = element_text(size = 12,hjust = 1,angle = 45,color = "black"),
axis.title.y = element_text(size = 12,color = "black"))

各組顯著性比較
載入數(shù)據(jù)
仍然使用mpg數(shù)據(jù)集,不過需要注意的是,將class變量變?yōu)橐蜃有?,因?yàn)檫@樣可以在對(duì)比過程中按照一定的順序依次進(jìn)行。compare_means函數(shù)能夠?qū)Σ煌兞窟M(jìn)行假設(shè)檢驗(yàn),com_list變量?jī)?chǔ)存了比較的不同分組,利用for循環(huán)生成兩兩配對(duì)的比對(duì)列表。
df <- mpg
df$class <- as.factor(df$class)
levels(df$class)
compare <- compare_means(hwy~class,df,method = "t.test")
com_list <- list()
for (i in 1:nrow(compare)){
com_list[[i]] <- c(compare$group1[i],compare$group2[i])
}
開始繪圖
該步驟使用ggplot繪圖,方法和之前的一樣,不過這里顯示了每個(gè)變量之間的兩兩比較結(jié)果。
ggplot(df,aes(class,hwy))+
geom_boxplot(aes(fill=class))+
stat_compare_means(comparisons = com_list,
test = "t.test",
step.increase = 0.1,
map_signif_level = T)+
theme_bw()+
scale_fill_jco()

本文由mdnice多平臺(tái)發(fā)布