部分示例數(shù)據(jù)如下

- 第一列是數(shù)值
- 第二列是處理一
-第三列是處理二
最終出圖如下

這里自動(dòng)做統(tǒng)計(jì)檢驗(yàn)的函數(shù)是 stat_compare_means()
首先是做箱線圖和小提琴圖的代碼
讀入數(shù)據(jù)
df<-read.csv("boxplot_example_1.csv",
header=T)
head(df)
作圖
library(ggplot2)
ggplot(data=df,aes(x=dose,y=len,fill=supp))+
geom_violin()+
geom_boxplot(width=0.2,
position = position_dodge(0.9))+
theme_bw()+
theme(panel.grid = element_blank())+
scale_fill_manual(values = c("yellowgreen", "violetred1"))

添加顯著性檢驗(yàn)的P值
這個(gè)函數(shù)來(lái)自于ggpubr這個(gè)包,只需要指定根據(jù)那一列來(lái)分組就可以了
library(ggpubr)
ggplot(data=df,aes(x=dose,y=len,fill=supp))+
geom_violin()+
geom_boxplot(width=0.2,
position = position_dodge(0.9))+
theme_bw()+
theme(panel.grid = element_blank())+
scale_fill_manual(values = c("yellowgreen", "violetred1"))+
stat_compare_means(aes(group=supp))
默認(rèn)的是Wilcoxon Rank Sum and Signed Rank Tests,如果要用t檢驗(yàn)指定method參數(shù)
ggplot(data=df,aes(x=dose,y=len,fill=supp))+
geom_violin()+
geom_boxplot(width=0.2,
position = position_dodge(0.9))+
theme_bw()+
theme(panel.grid = element_blank())+
scale_fill_manual(values = c("yellowgreen", "violetred1"))+
stat_compare_means(aes(group=supp),
method = "t.test")
如果想把P值改成星號(hào),直接加label=“p.signif”參數(shù)
ggplot(data=df,aes(x=dose,y=len,fill=supp))+
geom_violin()+
geom_boxplot(width=0.2,
position = position_dodge(0.9))+
theme_bw()+
theme(panel.grid = element_blank())+
scale_fill_manual(values = c("yellowgreen", "violetred1"))+
stat_compare_means(aes(group=supp),
method = "t.test",
label="p.signif")
這里如果不顯著會(huì)在圖上顯示ns,如果不想要ns,可以加hide.ns = TRUE參數(shù)
星號(hào)的位置可以手動(dòng)指定,用label.y = c(26,31)參數(shù)
接下來(lái)是添加線段
使用到的是ggsignif這個(gè)包
geom_signif(annotations = c("",""),
y_position = c(25,30),
xmin = c(0.8,1.8),
xmax = c(1.2,2.2),
tip_length = c(0.02,0.4,0.02,0.2))
annotations參數(shù)后指定線段上跟什么內(nèi)容,這里上面已經(jīng)自動(dòng)添加好星號(hào)了,所以不要任何內(nèi)容了y_position線段的位置xmin線段的最左端xmax線段的最右端tip_length線段的垂直長(zhǎng)度
完整代碼
df<-read.csv("boxplot_example_1.csv",
header=T)
head(df)
library(ggplot2)
library(ggpubr)
library(ggsignif)
ggplot(data=df,aes(x=dose,y=len,fill=supp))+
geom_violin()+
geom_boxplot(width=0.2,
position = position_dodge(0.9))+
theme_bw()+
theme(panel.grid = element_blank())+
scale_fill_manual(values = c("yellowgreen", "violetred1"))+
stat_compare_means(aes(group=supp),
label="p.signif",
method = "t.test",
hide.ns = TRUE,
label.y = c(26,31))+
geom_signif(annotations = c("",""),
y_position = c(25,30),
xmin = c(0.8,1.8),
xmax = c(1.2,2.2),
tip_length = c(0.02,0.4,0.02,0.2))
歡迎大家關(guān)注我的公眾號(hào)
小明的數(shù)據(jù)分析筆記本
小明的數(shù)據(jù)分析筆記本 公眾號(hào) 主要分享:1、R語(yǔ)言和python做數(shù)據(jù)分析和數(shù)據(jù)可視化的簡(jiǎn)單小例子;2、園藝植物相關(guān)轉(zhuǎn)錄組學(xué)、基因組學(xué)、群體遺傳學(xué)文獻(xiàn)閱讀筆記;3、生物信息學(xué)入門學(xué)習(xí)資料及自己的學(xué)習(xí)筆記!
今天的推文內(nèi)容會(huì)錄制視頻放到B站,歡迎大家關(guān)注我的B站賬號(hào) 小明的數(shù)據(jù)分析筆記本
