本文主要介绍在R语言中如何利用ggplot2绘制小提琴图(Violin Plot),小提琴一般可用于展示数据的分布状态以及密度特征。如下图所示:
1、数据准备
library(ggplot2)
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
str(ToothGrowth)
#'data.frame': 60 obs. of 3 variables:
# $ len : num 4.2 11.5 7.3 5.8 6.4 10 11.2 11.2 5.2 7 ...
# $ supp: Factor w/ 2 levels "OJ","VC": 2 2 2 2 2 2 2 2 2 2 ...
# $ dose: num 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 ...
ToothGrowth$dose <- factor(ToothGrowth$dose)
2、图形绘制
2.1 基础小提琴图
ggplot(ToothGrowth, aes(dose, len, fill = dose)) +
geom_violin(trim = FALSE, show.legend = FALSE) +
scale_fill_brewer(palette = "Set2") +
theme_bw(base_size = 15)
2.2 添加均值与标准差
添加均值点以及一个±标准差
ggplot(ToothGrowth, aes(dose, len, fill = dose)) +
geom_violin(trim = FALSE, show.legend = FALSE) +
stat_summary(fun.data = "mean_sdl", fun.args = list(mult = 1), geom = "pointrange", color = "black", show.legend = FALSE) +
scale_fill_brewer(palette = "Set2") +
theme_bw(base_size = 15)
2.3 添加箱线图
ggplot(ToothGrowth, aes(dose, len, fill = dose )) +
geom_violin(trim = FALSE, position = position_dodge(0.9), show.legend = FALSE) +
geom_boxplot(width = 0.2, position = position_dodge(0.9), show.legend = FALSE) +
scale_fill_brewer(palette = "Set2") +
theme_bw(base_size = 15)
2.4 分组变量下小提琴图
ggplot(ToothGrowth, aes(dose, len, fill = supp )) +
geom_violin(trim = FALSE, position = position_dodge(0.9)) +
geom_boxplot(width = 0.2, position = position_dodge(0.9)) +
scale_fill_brewer(palette = "Set2") +
theme_bw(base_size = 15)
3、其他
更多内容可关注微信公众号【日常分享的小懒猫】。
如有帮助请多多点赞哦!
文章转载自日常分享的小懒猫,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。