序
本文記錄了:
成圖如下所示:
小提琴圖+箱形圖的繪制,箱形圖放置小提琴圖內(nèi)部,并進行顯著性差異檢驗。
加載所需要的包
library(ggplot2)
library(ggpubr)
library(ggsci)
library(ggsignif)
查看示例數(shù)據(jù)
str(iris)
'data.frame': 150 obs. of 5 variables:
$ Sepal.Length: num 5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
$ Sepal.Width : num 3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
$ Petal.Length: num 1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
$ Petal.Width : num 0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
$ Species : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
table(iris$Species)
setosa versicolor virginica
50 50 50
成圖
ggplot(iris, aes(x = Species, y = Sepal.Length, fill = Species)) +
geom_violin(trim = FALSE, alpha = 0.5) +
geom_boxplot(
width = 0.1, # 箱子寬度,使其能縮進在小提琴里
fill = "white",
outlier.shape = 0 # 將離群點畫為一個小方塊,要隱藏則設置為NA
) +
# 添加誤差線
stat_boxplot(
geom = "errorbar",
position = position_dodge(width = 0.1),
width = 0.1
) +
# 添加散點
geom_jitter(
width = 0.2, alpha = 0.3
)+
# ggpubr
theme_pubr() + # 主題先設置,不然會覆蓋后續(xù)的微調(diào)。
labs(
title = "Violin Plot with Boxplot",
subtitle = "Fisher's Iris Data",
x = "Species",
y = "Sepal Length",
caption = "Statistics: Pairwise Wilcoxon rank sum test; *** p < 0.001"
) +
theme(
axis.text.x = element_text(angle = 45, hjust = 1),
legend.title = element_blank()
)+
# ggsci
scale_fill_manual(
values = ggsci::pal_aaas()(3)
) +
# ggsignif
geom_signif(
test = "wilcox.test", # default.
comparisons = list(
c("setosa", "versicolor"), # 設置誰與誰比較
c("setosa", "virginica"),
c("versicolor", "virginica")
),
step_increase = 0.1, # 當有多個對比線時,每根線向上錯開 10%,防止重疊
map_signif_level = FALSE # 設置為F(default),表示直接顯示具體的 P 值數(shù)值,而不是星號(***)
)

