R可视化和ggplot2

《R数据可视化手册》学习笔记6---描述数据分布(8)小提琴图

2023-10-09  本文已影响0人  RSP小白之路

写在前面。

这篇文章对应原书的第6章,主要介绍一些描述数据分布的可视化图形。主要包括如下这些:


小提琴图

如何绘制小提琴图以对各组数据的密度估计进行比较呢?

示例数据heightweight数据集:

> str(heightweight)
'data.frame':   236 obs. of  5 variables:
 $ sex     : Factor w/ 2 levels "f","m": 1 1 1 1 1 1 1 1 1 1 ...
 $ ageYear : num  11.9 12.9 12.8 13.4 15.9 ...
 $ ageMonth: int  143 155 153 161 191 171 185 142 160 140 ...
 $ heightIn: num  56.3 62.3 63.3 59 62.5 62.5 59 56.5 62 53.8 ...
 $ weightLb: num  85 105 108 92 112 ...

使用geom_violin函数即可。

ggplot(data = heightweight, aes(x = sex, y = heightIn)) + geom_violin()

[图片上传失败...(image-8576bb-1696889849634)]

小提琴图也是核密度估计,取核密度曲线的镜像使形状对称。弥补了密度图进行多组绘图时的彼此干扰的问题。

传统绘图会在小提琴图中间叠加一个箱线图,并显示中位数为白圈

ggplot(data = heightweight, aes(x = sex, y = heightIn)) +
  geom_violin()+
  geom_boxplot(width = 0.1, fill = "grey", outlier.colour = NA)+
  stat_summary(fun = median, geom = "point", fill = "white", shape = 1, size = 2.5)

[图片上传失败...(image-bdc84e-1696889849634)]

outlier.colour = NA选项用于清除异常点

可以看到,尾部是被截断的,可以使用选项trim=FALSE使尾部不截断。

通常情况下,默认会对数据进行标准化,使图形面积一致,可以使用scale=count设置不进行标准化,使每组小提琴图的面积和计数成正比

ggplot(data = heightweight, aes(x = sex, y = heightIn)) +
  geom_violin(scale = "count", trim = FALSE)+
  geom_boxplot(width = 0.1, fill = "grey", outlier.colour = NA)+
  stat_summary(fun = median, geom = "point", fill = "white", shape = 1, size = 2.5)

[图片上传失败...(image-19e9aa-1696889849634)]

核密度图一样,平滑程度也可以使用adjust进行调整:

ggplot(data = heightweight, aes(x = sex, y = heightIn)) +
  geom_violin(scale = "count", trim = FALSE, adjust = 0.5)+
  stat_summary(fun = median, geom = "point", fill = "white", shape = 1, size = 2.5)

[图片上传失败...(image-28f8a9-1696889849634)]

上一篇下一篇

猜你喜欢

热点阅读