下面将介绍如何使用ggplot2制作Sinaplot,并说明为什么它是一种更好的可视化方式

Google对Sinaplot的定义
Sinaplot受到条形图和小提琴图的启发。该图显示了与小提琴图相同的轮廓,适合于在多类数据集中绘制任何单个变量的数据可视化图表。它是增强版的抖动条形图,其中抖动的宽度由每个类别内数据的密度分布控制
加载R包
library(tidyverse)
library(ggforce)
library(patchwork)
构造3个数据集合,第一个双峰分布,第二个均匀分布,第三个正态分布
bimodal <- c(rnorm(100,4),rnorm(100,8))
uniform <- c(runif(200,min=4,max=8))
normal <- c(rnorm(200,6,sd=3))
> head(df)
bimodal uniform normal
1 3.491757 4.801792 3.055745
2 3.246869 5.113854 2.768095
3 0.569459 6.232528 7.323789
4 3.206453 6.320274 9.293444
5 3.266438 7.534436 8.599974
6 3.722091 4.867614 5.959940
使用tidyr包中的pivot_longer( )将数据以宽格式转换为长格式
p <- data.frame(bimodal=bimodal,
uniform=uniform,
normal=normal)
df <- p %>%
pivot_longer(cols=bimodal:normal,
values_to = "value", names_to = "grp")
> df
# A tibble: 600 x 2
grp value
<chr> <dbl>
1 bimodal 3.49
2 uniform 4.80
3 normal 3.06
4 bimodal 3.25
先绘制一个箱线图,可以看到三个分布看起来都一样。箱线图基本上掩盖了数据的真实性
df %>%
ggplot(aes(x=grp,y=value, fill=grp))+
geom_boxplot()+
theme(legend.position = "none")

绘制小提琴图,该图将密度层添加到箱图中,Violinplot很好地展示了数据的真实分布情况
df %>%
ggplot(aes(x=grp,y=value, fill=grp))+
geom_violin()+
theme(legend.position = "none")

具有抖动数据点的Violinplot比单独的Violinplot更好
Violinplot仍然依靠汇总统计信息,并且不显示该图后面的实际数据。因此,更好的选择是将抖动数据点添加到小提琴图
df %>%
ggplot(aes(x=grp,y=value,fill=grp))+
geom_violin()+
geom_jitter(width=0.1,alpha=0.5)+
theme(legend.position="none")

Sinaplot比Violinplot更好
带有抖动数据点的小提琴图显示了数据分布模式。但是抖动的数据点仍然可以彼此重叠,并且不能完全看到数据。而Sinaplot结合了抖动数据点和小提琴图的优点。使用ggforce的geom_sina()函数制作sinaplot
df %>%
ggplot(aes(x=grp,y=value, color=grp))+
geom_sina()+
theme(legend.position="none")

结合Vioplot的Sinaplot比单独的Sinaplot更好
尽管sinaplot nices很好地显示了数据及其密度模式,但在其中添加在小提琴图中使其看起来更好
df %>%
ggplot(aes(x=grp,y=value, fill=grp))+
geom_violin()+
geom_sina(alpha=0.5)+
theme(legend.position="none")

网友评论