如何在R语言的小提琴图中添加含分位数的统计表格?
在R语言的小提琴图中添加统计表格的实现方法
完全可以实现,下面是具体步骤和代码:
1. 预处理数据
首先你的Range列是字符类型,需要先转为数值型才能计算分位数:
vp4melted$Range <- as.numeric(vp4melted$Range)
2. 计算所需统计量
用dplyr包按Diabetes分组,计算25%分位数、中位数、75%分位数:
library(dplyr) stats_table <- vp4melted %>% group_by(Diabetes) %>% summarise( "25%分位数" = quantile(Range, 0.25), "中位数" = median(Range), "75%分位数" = quantile(Range, 0.75) ) %>% ungroup()
3. 绘制小提琴图+箱线图
保留你原有的绘图代码,优化后去掉冗余图例:
library(ggplot2) p <- ggplot(vp4melted, aes(x = Diabetes, y = Range, fill = Diabetes)) + geom_violin(trim = FALSE) + theme_classic() + stat_summary(fun = mean, geom = "point", size = 2, color = "red") + geom_boxplot(width = 0.1) + theme(legend.position = "none") # x轴分组已清晰展示类别,无需重复图例
4. 组合图与统计表格
这里用patchwork包将图和表格并排展示(也可以用gridExtra包,代码逻辑类似):
library(patchwork) # 将统计表格转为ggplot格式的文本图 table_plot <- ggplot() + # 分组标题 geom_text(data = stats_table, aes(x = 1, y = 4, label = Diabetes), fontface = "bold", hjust = 0, size = 4) + # 统计内容 geom_text(data = stats_table, aes(x = 1, y = 3, label = paste0("25%分位数: ", `25%分位数`)), hjust = 0, size = 3.5) + geom_text(data = stats_table, aes(x = 1, y = 2, label = paste0("中位数: ", 中位数)), hjust = 0, size = 3.5) + geom_text(data = stats_table, aes(x = 1, y = 1, label = paste0("75%分位数: ", `75%分位数`)), hjust = 0, size = 3.5) + theme_void() + coord_cartesian(xlim = c(1, 2)) # 调整宽度避免文本被截断 # 组合图和表格,设置宽度比例 p + table_plot + plot_layout(widths = c(3, 1))
如果偏好更规整的表格样式,可改用gridExtra的tableGrob:
library(gridExtra) grid.arrange(p, tableGrob(stats_table, rows = NULL), ncol = 2, widths = c(3, 1))
内容的提问来源于stack exchange,提问作者Ray
相关产品推荐
相关产品推荐

