ggplot使用geom_split_violin绘制按性别拆分的单分组小提琴图
单分组拆分小提琴图实现方案
不需要修改你现有geom_split_violin的自定义函数代码,仅需调整ggplot的映射参数即可实现:
- 核心逻辑:原函数通过分组的group序号奇偶性决定左右摆放位置,单分组场景下将
x映射为固定值(无需多分类x变量)即可让两个性别分组的小提琴在同一个x轴位置拆分展示。
完整示例代码
首先保留你现有的自定义函数代码:
GeomSplitViolin <- ggproto("GeomSplitViolin", GeomViolin, draw_group = function(self, data, ..., draw_quantiles = NULL) { data <- transform(data, xminv = x - violinwidth * (x - xmin), xmaxv = x + violinwidth * (xmax - x)) grp <- data[1, "group"] newdata <- plyr::arrange(transform(data, x = if (grp %% 2 == 1) xminv else xmaxv), if (grp %% 2 == 1) y else -y) newdata <- rbind(newdata[1, ], newdata, newdata[nrow(newdata), ], newdata[1, ]) newdata[c(1, nrow(newdata) - 1, nrow(newdata)), "x"] <- round(newdata[1, "x"]) if (length(draw_quantiles) > 0 & !scales::zero_range(range(data$y))) { stopifnot(all(draw_quantiles >= 0), all(draw_quantiles <= 1)) quantiles <- ggplot2:::create_quantile_segment_frame(data, draw_quantiles) aesthetics <- data[rep(1, nrow(quantiles)), setdiff(names(data), c("x", "y")), drop = FALSE] aesthetics$alpha <- rep(1, nrow(quantiles)) both <- cbind(quantiles, aesthetics) quantile_grob <- GeomPath$draw_panel(both, ...) ggplot2:::ggname("geom_split_violin", grid::grobTree(GeomPolygon$draw_panel(newdata, ...), quantile_grob)) } else { ggplot2:::ggname("geom_split_violin", GeomPolygon$draw_panel(newdata, ...)) } }) geom_split_violin <- function(mapping = NULL, data = NULL, stat = "ydensity", position = "identity", ..., draw_quantiles = NULL, trim = TRUE, scale = "area", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE) { layer(data = data, mapping = mapping, stat = stat, geom = GeomSplitViolin, position = position, show.legend = show.legend, inherit.aes = inherit.aes, params = list(trim = trim, scale = scale, draw_quantiles = draw_quantiles, na.rm = na.rm, ...)) }
然后构造示例数据+绘图:
# 构造示例数据:仅包含性别和测量值两个字段 my_data <- data.frame( 性别 = sample(c("男", "女"), 1000, replace = TRUE) ) my_data$测量值 <- rnorm(1000, mean = c(0, 1.2)[as.factor(my_data$性别)]) # 单分组拆分小提琴图绘制 ggplot(my_data, aes(x = "总样本", y = 测量值, fill = 性别)) + geom_split_violin(trim = FALSE) + # 可选优化:去掉x轴无用标签,调整主题 labs(x = NULL) + theme_classic()
如果需要展示分位数线,直接加draw_quantiles参数即可,比如展示中位数:
ggplot(my_data, aes(x = "总样本", y = 测量值, fill = 性别)) + geom_split_violin(trim = FALSE, draw_quantiles = 0.5) + labs(x = NULL) + theme_classic()
内容的提问来源于stack exchange,提问作者Volkerballoon
相关产品推荐
相关产品推荐

