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

在R语言中创建双层Donut Chart(环形图)遇到问题求助

R语言实现双层环形图(Donut Chart)

数据准备

先把你的数据集载入R(如果还没加载的话):

DATA <- data.frame(
  PRODUCT = c("GEN", "PHA", "FRE", "JUM", "PRC", "POW", "ALI"),
  REV = c(40, 20, 10, 10, 15, 3, 3),
  PRO = c(50, 20, 9, 5, 2, 3, 11)
)

数据预处理

将宽格式数据转为长格式,并计算每个产品在收入(REV)、利润(PRO)中的占比:

library(tidyverse)

data_long <- DATA %>%
  pivot_longer(cols = c(REV, PRO), names_to = "Metric", values_to = "Value") %>%
  group_by(Metric) %>%
  mutate(Percent = Value / sum(Value) * 100,
         Label = paste0(round(Percent, 1), "%"))

绘制双层环形图

使用ggplot2绘制,通过调整x轴刻度实现双层环形,同一产品对应相同颜色:

ggplot(data_long, aes(x = Metric, y = Percent, fill = PRODUCT)) +
  geom_col(width = 0.7, position = position_stack(reverse = TRUE)) +
  # 添加百分比标签
  geom_text(aes(label = Label), 
            position = position_stack(reverse = TRUE, vjust = 0.5),
            size = 3) +
  # 转为极坐标形成环形
  coord_polar("y") +
  # 调整x轴刻度位置,拉开内外层间距
  scale_x_discrete(limits = c("PRO", "REV"), expand = c(0.2, 0)) +
  # 用渐变配色区分产品(可自定义)
  scale_fill_viridis_d() +
  # 移除冗余坐标轴元素
  theme_void() +
  # 添加图例和标题
  labs(fill = "产品", title = "收入与利润双层环形占比图") +
  theme(legend.position = "right",
        plot.title = element_text(hjust = 0.5, size = 14))

自定义说明

  • 外层对应收入(REV),内层对应利润(PRO),同一产品颜色完全匹配
  • 可通过geom_col的width参数调整环形粗细,scale_x_discrete的expand参数调整内外层间距
  • 若要指定专属颜色,替换scale_fill_viridis_d()为scale_fill_manual(values = c("GEN" = "#FF5733", "PHA" = "#33FF57", ...)),手动设置每个产品的颜色值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 14:15:16