https://www.leansigmacorporation.com/box-plot-with-minitab/
0、加载包和示例数据
library(ggplot2)
library(patchwork)
#组别名最好是字符型;如果是数值类型,最好转为因子化
ToothGrowth$dose = factor(ToothGrowth$dose)
summary(ToothGrowth)
# len supp dose
# Min. : 4.20 OJ:30 0.5:20
# 1st Qu.:13.07 VC:30 1 :20
# Median :19.25 2 :20
# Mean :18.81
# 3rd Qu.:25.27
# Max. :33.90
head(ToothGrowth)
# len supp dose
# 1 4.2 VC 0.5
# 2 11.5 VC 0.5
# 3 7.3 VC 0.5
# 4 5.8 VC 0.5
# 5 6.4 VC 0.5
# 6 10.0 VC 0.5
Each animal received one of three dose levels of vitamin C (0.5, 1, and 2 mg/day) by one of two delivery methods, orange juice or ascorbic acid
1、基础绘图
# x 指定组名列;
# y 指定值的列
p1 = ggplot(ToothGrowth, aes(x=dose, y=len, fill=dose)) +
geom_boxplot()
p2 = ggplot(ToothGrowth, aes(x=dose, y=len, fill=supp)) +
geom_boxplot()
p1 | p2
2、离群点相关
?geom_boxplot
p1 = ggplot(ToothGrowth, aes(x=dose, y=len)) +
geom_boxplot(outlier.color = "red",
outlier.size = 0.5)
p2 = ggplot(ToothGrowth, aes(x=dose, y=len)) +
geom_boxplot(outlier.alpha = 0) #透明度为0,相当于不绘制离群点
p1 + p2
3、随机抖动点
ggplot(ToothGrowth, aes(x=dose, y=len)) +
geom_boxplot(outlier.color = "red") +
geom_jitter(color = "black", size=0.8)
4、给箱图添加whisker须线
ggplot(ToothGrowth, aes(x=dose, y=len)) +
stat_boxplot(geom = "errorbar", width = 0.2) +
geom_boxplot()
5、小提琴图
p1 = ggplot(ToothGrowth, aes(x=dose, y=len, fill=dose)) +
geom_violin()
p2 = ggplot(ToothGrowth, aes(x=dose, y=len, fill=dose)) +
geom_violin() +
geom_boxplot(width=0.2, color="black", alpha=0.5)
p1 | p2
6、排序
- 按照每组的均值等依次降序/升序排列箱图的顺序
参考之前笔记:https://www.jianshu.com/p/552bee6119ad -
scale_x_discrete()
自定义排列顺序
ggplot(ToothGrowth, aes(x=dose, y=len)) +
geom_boxplot() +
scale_x_discrete(limits=c("1","2","0.5"))
7、一键生成复杂箱图
library(ggstatsplot)
ggbetweenstats(
data = ToothGrowth,
x = dose,
y = len
)
在下一小节,会学习如何使用
ggpubr
包对箱图组间比较注释p值结果。
网友评论