今天介绍一个R包{ggdist},能画出多种图型展示数据分布情况,还能与{ggplot2}兼容。install.packages("ggdist")
library(ggdist)
library(ggplot2) # install.packages("ggplot2")
library(distributional) # install.packages("distributional")
library(patchwork) # install.packages("patchwork")
set.seed(000)
mydata <- data.frame(
groups = LETTERS[1:4],
values = rnorm(1000, mean = c(2, 8, 5, 7), sd = c(1, 1.5, 2, 5)),
types = c(rep("T1", 4), rep("T2", 4))
)
summary(mydata)
mydata1 <- data.frame(
groups = LETTERS[1:4],
mean = c(2, 8, 5, 7),
sd = c(1, 1.5, 2, 5)
)
mydata1
假设需要查看数据中多组间的分布情况,可以画一个slab plot:
ggplot(mydata, aes(x = groups, y = values, fill = groups)) +
stat_slabinterval(geom = "slab") + # 相当于 stat_slab()
theme_ggdist()
假设已经知道数据的均数和标准差,画出四种不同分布情况的图:ggplot(mydata1, aes(y = groups, xdist = dist_normal(mean, sd))) +
stat_slab(colour = "skyblue") +
theme_ggdist()
再来,假如想画eye plot 和 half-eye plots来观察数据分布:
p1 <- ggplot(mydata, aes(x = groups, y = values, fill = groups)) +
stat_slabinterval(show.legend = FALSE) + # 相当于 stat_halfeye()
ggtitle('side = "right"') +
theme_ggdist()
p2 <- ggplot(mydata, aes(x = groups, y = values, fill = groups)) +
stat_slabinterval(side = "left",
show.legend = FALSE) +
ggtitle('side = "left"') +
theme_ggdist()
p3 <- ggplot(mydata, aes(x = groups, y = values, fill = groups)) +
stat_slabinterval(side = "both") + # 相当于 stat_eye()
ggtitle('side = "both"') +
theme_ggdist()
p1+p2+p3
上图中分别画出了右half-eye plot、左half-eye plot,和eye plot。除了上面的几种图形外,也常常使用直方图来观察数据分布,这个就看各位喜好了。假设想画直方图,还是直接使用stat_slabinterval():ggplot(mydata, aes(x = groups, y = values, fill = groups)) +
stat_slabinterval(density = "histogram") # stat_histinterval()
ggplot(mydata, aes(x = groups, y = values, fill = groups)) +
stat_histinterval(slab_color = "grey",
outline_bars = TRUE)+
theme_ggdist()
如果数据点不多的情况下,可以画个多组别的dots plot(点图):ggplot(mydata, aes(x = types, y = values, colour = groups)) +
stat_dots(position = "dodge")
如果想在点图的基础上,再加interval plot,可以使用stat_dotsinterval():ggplot(mydata, aes(x = groups, y = values, colour = groups)) +
stat_dotsinterval(slab_color = "skyblue") +
theme_ggdist()
好啦,今天的内容就到这里。如果有帮助,记得分享给需要的人![1]. https://mjskay.github.io/ggdist/
公众号核心成员担任SCI杂志Associate Editor!▌课程相关咨询可添加R师妹微信: kefu_rstats