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

在R中绘制三级层级饼图(环形图)失败求助

三级层级环形图(甜甜圈图)实现方案(R语言)

数据预处理

首先需按Phylum > Class > Family层级分组统计物种数量,为环形图提供各分类单元的计数数据:

# 加载依赖包
library(tidyverse)

# 分组统计各层级物种数(假设你的数据集名为df2)
df_summary <- df2 %>%
  group_by(Phylum, Class, Family) %>%
  summarise(count = n(), .groups = "drop") %>%
  # 计算各层级的累计数量,用于区分环形层级
  mutate(
    class_total = ave(count, Phylum, Class, FUN = sum),
    phylum_total = ave(count, Phylum, FUN = sum)
  )

绘制三级环形图

使用ggplot2构建三层环形结构,通过调整x轴数值区分不同层级:

ggplot() +
  # 最外层:Family层级
  geom_bar(
    data = df_summary,
    aes(x = 3, y = count, fill = Family),
    stat = "identity",
    width = 1
  ) +
  # 中间层:Class层级
  geom_bar(
    data = df_summary %>% distinct(Phylum, Class, .keep_all = TRUE),
    aes(x = 2, y = class_total, fill = Class),
    stat = "identity",
    width = 1
  ) +
  # 最内层:Phylum层级
  geom_bar(
    data = df_summary %>% distinct(Phylum, .keep_all = TRUE),
    aes(x = 1, y = phylum_total, fill = Phylum),
    stat = "identity",
    width = 1
  ) +
  # 转换为极坐标,形成环形
  coord_polar(theta = "y") +
  # 设置x轴刻度对应层级名称
  scale_x_continuous(breaks = c(1, 2, 3), labels = c("Phylum", "Class", "Family")) +
  # 优化主题样式
  theme_minimal() +
  theme(
    axis.text.y = element_blank(),
    axis.ticks = element_blank(),
    panel.grid = element_blank(),
    legend.position = "right",
    plot.title = element_text(hjust = 0.5, size = 16)
  ) +
  labs(title = "物种分类三级环形图", x = "", y = "")

可选优化方案

若层级过多导致图例混乱,可尝试旭日图更直观展示层级关系:

library(sunburstR)

# 转换为旭日图所需格式
df_sunburst <- df_summary %>%
  mutate(path = paste(Phylum, Class, Family, sep = "-")) %>%
  select(path, count)

# 绘制旭日图
sunburst(df_sunburst)

内容的提问来源于stack exchange,提问作者Isma Soto Almena

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 06:17:01