如何在R语言中绘制可区分子组的分层环形图(基于Titanic数据集)
用R绘制Titanic数据集的分层环形图(自定义层级宽度)
问题分析
你需要的是4个层级、每个子组对应不同宽度的分层环形图,之前用ggdonutchart或PieDonut的问题在于前者无法自定义层级宽度,后者因重复分组键报错。下面用ggplot2直接构建自定义分层环形,完全匹配你的需求。
实现代码
1. 加载依赖包并处理数据
library(tidyverse) # 转换Titanic为数据框,计算各舱级总人数 titanic_df <- as.data.frame(Titanic) %>% group_by(Class) %>% summarise(total = sum(Freq)) %>% ungroup() # 定义舱级颜色(严格匹配需求) class_colors <- c("1st" = "darkblue", "2nd" = "blue", "3rd" = "lightblue", "Crew" = "gray") # 定义各层级宽度(数值越大层越宽,可自行调整) level_widths <- c("1st" = 0.3, "2nd" = 0.25, "3rd" = 0.2, "Crew" = 0.15) # 生成绘图所需的坐标数据(计算每个环形区块的极坐标范围) plot_data <- titanic_df %>% mutate( # 计算每个层级的内外半径 inner_radius = cumsum(lag(level_widths[match(Class, names(level_widths))], default = 0)), outer_radius = inner_radius + level_widths[match(Class, names(level_widths))], # 计算每个舱级的角度范围(弧度制) start_angle = cumsum(lag(2 * pi * total / sum(total), default = 0)), end_angle = start_angle + 2 * pi * total / sum(total) ) %>% # 展开为矩形区块的四个顶点坐标(适配geom_rect) rowwise() %>% mutate( xmin = inner_radius * cos(start_angle), ymin = inner_radius * sin(start_angle), xmax = outer_radius * cos(start_angle), ymax = outer_radius * sin(start_angle), xmin2 = inner_radius * cos(end_angle), ymin2 = inner_radius * sin(end_angle), xmax2 = outer_radius * cos(end_angle), ymax2 = outer_radius * sin(end_angle) ) %>% ungroup()
2. 绘制分层环形图
ggplot() + # 添加每个舱级的环形区块 geom_rect( data = plot_data, aes( xmin = xmin, ymin = ymin, xmax = xmax, ymax = ymax, xmin2 = xmin2, ymin2 = ymin2, xmax2 = xmax2, ymax2 = ymax2, fill = Class ), color = "white" # 区块间白色分隔线,增强可读性 ) + # 转换为极坐标,生成环形效果 coord_polar(start = 0) + # 应用自定义颜色映射 scale_fill_manual(values = class_colors) + # 清理主题,去掉冗余元素 theme_void() + theme( legend.title = element_text(hjust = 0.5), legend.position = "bottom" ) + labs(title = "Titanic 舱级分层环形图", fill = "舱级")
关键说明
- 自定义层级宽度:修改
level_widths向量即可调整各层的宽度,数值越大对应层级越宽 - 颜色完全匹配需求:1等舱深蓝、2等舱蓝色、3等舱浅蓝、船员舱灰色
- 避开
PieDonut报错:直接用geom_rect构建环形,无需依赖分组键唯一的限制
内容的提问来源于stack exchange,提问作者MicL
相关产品推荐
相关产品推荐

