序
本文记录了:
成图如下所示:
小提琴图+箱形图的绘制,箱形图放置小提琴图内部,并进行显著性差异检验。
加载所需要的包
library(ggplot2)
library(ggpubr)
library(ggsci)
library(ggsignif)
查看示例数据
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() + # 主题先设置,不然会覆盖后续的微调。
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 值数值,而不是星号(***)
)

