You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R语言中绘制三层环形图(Donut Chart)?

问题:在R中实现三层环形图

尝试在R语言中重现目标三层环形图,但无法实现三层结构——找到的工具(例如webr::PieDonut)仅支持两层,使用ggplot也无法完成复刻。以下是最小可复现示例(MRE):

library(ggplot2)
library(webr)
library(dplyr)

lexicon <- data.frame("Level1" = c(rep("Flavour", 11), rep("Appearance", 4)),
                  "Level2" = c(rep("Misc", 6), rep("Pungent", 5), rep("Colour", 4)),
                  "Level3" = c("Fresh", "Refreshing", "Soapy", "Minty", "Nutty", "Milky", "Peppery", "Sharp", "Horseradish", "Mustard hot", "Spicy", "Colourful"," Fresh Green", "Dark Green", "Bright Green")
)

PieDonut(lexicon, aes(Level1, Level2), title = "Salad Lexicon", showRatioDonut =FALSE, showRatioPie = FALSE)

ggplot(lexicon, aes(Level2, Level3, fill = Level1)) +
  geom_col() +
  scale_fill_viridis_d() +
  coord_polar("y")

其中PieDonut仅能处理Level1和Level2两层,无法纳入Level3;ggplot的极坐标柱状图也达不到预期效果。请问如何使用ggplot或基础绘图在R中实现该样式的图表?


解决方案:用ggplot实现三层环形图

通过将多层数据整理为长格式,给每个层级分配不同的环形半径,结合geom_col和极坐标转换,即可实现三层环形图:

library(ggplot2)
library(dplyr)
library(tidyr)

# 原始数据
lexicon <- data.frame(
  Level1 = c(rep("Flavour", 11), rep("Appearance", 4)),
  Level2 = c(rep("Misc", 6), rep("Pungent", 5), rep("Colour", 4)),
  Level3 = c("Fresh", "Refreshing", "Soapy", "Minty", "Nutty", "Milky", 
             "Peppery", "Sharp", "Horseradish", "Mustard hot", "Spicy", 
             "Colourful", "Fresh Green", "Dark Green", "Bright Green")
)

# 整理数据:统计各层级类别的数量,分配环形层级
level_data <- bind_rows(
  # Level1:最外层环
  lexicon %>% count(Level1) %>% mutate(level = "Level1", category = Level1, ring = 3),
  # Level2:中间层环
  lexicon %>% count(Level2) %>% mutate(level = "Level2", category = Level2, ring = 2),
  # Level3:最内层环
  lexicon %>% count(Level3) %>% mutate(level = "Level3", category = Level3, ring = 1)
) %>% arrange(level, category)

# 绘制三层环形图
ggplot(level_data, aes(x = ring, y = n, fill = category)) +
  # 绘制柱状图,设置宽度控制环形厚度
  geom_col(width = 0.8, position = position_stack(reverse = TRUE)) +
  # 转换为极坐标
  coord_polar("y") +
  # 清理主题,隐藏冗余元素
  theme_void() +
  # 设置配色(可按需替换)
  scale_fill_viridis_d(option = "plasma") +
  # 添加类别标签(可选,调整size控制字体大小)
  geom_text(aes(label = category), 
            position = position_stack(vjust = 0.5, reverse = TRUE), 
            size = 3) +
  # 添加标题
  labs(title = "Salad Lexicon")

关键说明:

  • 数据整理:将三个层级的类别分别统计数量,通过ring字段区分环形的半径(数值越大,环形越靠外)。
  • 环形厚度:通过geom_col的width参数调整每层环形的厚度。
  • 堆叠顺序:position_stack(reverse = TRUE)确保类别堆叠顺序符合直观的环形逻辑。
  • 自定义调整:可修改ring的数值、width大小、配色方案或标签样式,适配需求。

内容的提问来源于stack exchange,提问作者Beavis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 06:54:23