在R语言中绘制三层饼图的方法与工具咨询
在R语言中绘制三层饼图的方法
你可以通过以下几种R包实现类似需求的三层饼图(环形层级饼图/旭日图),以下是具体方案:
一、使用ggplot2绘制静态三层环形饼图
首先需要预处理数据统计各层级的频数,再通过极坐标转换实现环形效果:
1. 数据预处理
library(dplyr) # 统计各层级组合的频数及对应父层级的总计数 dat_count <- dat %>% count(Type1, Type2, Type3, name = "count") %>% group_by(Type1) %>% mutate(Type1_total = sum(count)) %>% ungroup() %>% group_by(Type1, Type2) %>% mutate(Type2_total = sum(count)) %>% ungroup()
2. 绘制三层环形饼图
library(ggplot2) # 定义各层级的半径范围 level_radii <- c(0, 1, 2, 3) ggplot() + # 最外层:Type3 geom_bar(data = dat_count, aes(x = factor(3), y = count, fill = Type3), stat = "identity", width = 1) + # 中间层:Type2 geom_bar(data = dat_count %>% distinct(Type1, Type2, Type2_total, Type1_total), aes(x = factor(2), y = Type2_total, fill = Type2), stat = "identity", width = 1) + # 最内层:Type1 geom_bar(data = dat_count %>% distinct(Type1, Type1_total), aes(x = factor(1), y = Type1_total, fill = Type1), stat = "identity", width = 1) + # 转换为极坐标,形成环形结构 coord_polar(theta = "y") + # 配置轴刻度与范围 scale_x_discrete(limits = factor(1:3), expand = c(0, 0)) + scale_y_continuous(limits = c(0, max(level_radii))) + # 清理主题样式 theme_void() + # 设置图例位置 theme(legend.position = "right")
二、使用plotly绘制交互式旭日图(三层饼图变体)
如果需要交互式的层级饼图,plotly的旭日图可以直观展示三层分类的嵌套关系:
library(plotly) library(dplyr) # 整理为plotly所需的层级数据格式 dat_plotly <- dat %>% count(Type1, Type2, Type3, name = "values") %>% # 构建父节点关系 mutate(parents = paste(Type1, Type2, sep = "-"), labels = Type3) %>% # 添加Type2层级节点 bind_rows( dat %>% count(Type1, Type2, name = "values") %>% mutate(parents = Type1, labels = Type2) ) %>% # 添加Type1层级节点 bind_rows( dat %>% count(Type1, name = "values") %>% mutate(parents = "", labels = Type1) ) # 绘制交互式旭日图 plot_ly(dat_plotly, labels = ~labels, parents = ~parents, values = ~values, type = 'sunburst', branchvalues = 'total')
以上两种方法都可以实现类似参考图的三层分类饼图效果,静态图适合导出报告,交互式图便于查看细节。
内容的提问来源于stack exchange,提问作者Bertram
相关产品推荐
相关产品推荐

