最近有个需求,统计课中需要绘制以下图形:
这里我主要使用 ggridges
包中的 stat_density_ridges()
。这个包的介绍,小编以前做过一期内容,可见:ggridges包—峰峦图详细介绍。读者需要进一步阅读课件这篇博文[1],以及一些案例[2]。
library(ggplot2)
library(ggridges)
假设数据来源于一个混合分布。
item <- 10000
inds <- rbinom(1, item, 0.5)
x <- c(rnorm(inds, 1, 1), rnorm(item - inds, 8, 1))
data <- data.frame("value" = x, "class" = rep(1, length(x)))
# 绘图
p1 <- ggplot(data, aes(x = value, y = class, fill = factor(stat(quantile)))) +
stat_density_ridges(
geom = "density_ridges_gradient",
calc_ecdf = TRUE,
quantiles = c(0.025, 0.975) #添加分为数线
) +
scale_fill_manual(
name = "Probability", values = c("#E2EAF6", "#436FB0", "#E2EAF6")
) +
theme_bw() +
theme(legend.position = "none", panel.grid = element_blank()) +
labs(x = "x", y = "Density")
p1
p2 <- ggplot(data, aes(x = value, y = class, fill = factor(stat(quantile)))) +
stat_density_ridges(
geom = "density_ridges_gradient",
calc_ecdf = TRUE,
quantiles = c(0.005, 0.495, 0.51, 0.99)
) +
scale_fill_manual(
name = "Probability", values = c("#E2EAF6", "#436FB0", "#E2EAF6", "#436FB0", "#E2EAF6"),
) +
theme_bw() +
theme(legend.position = "none", panel.grid = element_blank()) +
labs(x = "x", y = "Density")
p2
使用 cowplot[3] 包,将两图进行合并。小编对该包的介绍做过几期,可见:cowplot包:用R添加水印。其他合并的方式还有:R可视乎|合并多幅图形;R可视乎|分面一页多图。
library(cowplot)
# pdf("plot_cow.pdf", width = 8, height = 4)
plot_grid(p1, p2, ncol = 1, nrow = 2)
# dev.off()