R-ggplot2-箱圖系列(1) basic - 簡(jiǎn)書(shū) (jianshu.com)
R-ggplot2-箱圖系列(2) 注釋P值與組間比較 - 簡(jiǎn)書(shū) (jianshu.com)
https://www.leansigmacorporation.com/box-plot-with-minitab/
0、加載包和示例數(shù)據(jù)
library(ggplot2)
library(patchwork)
#組別名最好是字符型;如果是數(shù)值類型,最好轉(zhuǎn)為因子化
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、基礎(chǔ)繪圖
# 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、離群點(diǎn)相關(guān)
?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,相當(dāng)于不繪制離群點(diǎn)
p1 + p2
3、隨機(jī)抖動(dòng)點(diǎn)
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、排序
- 按照每組的均值等依次降序/升序排列箱圖的順序
參考之前筆記:http://www.lxweimin.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、一鍵生成復(fù)雜箱圖
library(ggstatsplot)
ggbetweenstats(
data = ToothGrowth,
x = dose,
y = len
)
在下一小節(jié),會(huì)學(xué)習(xí)如何使用
ggpubr
包對(duì)箱圖組間比較注釋p值結(jié)果。