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

R语言ggplot2分组堆叠环形柱状图标签定位优化需求

解决ggplot2分组堆叠环形柱状图的两个问题

1. 修复比例标签位置偏移问题

要让标签精准对应堆叠区域,核心是计算每个堆叠块的中心位置,而非直接使用原始数值。用dplyr对数据分组计算累积值,得到每个块的起始、结束位置,再取中点作为标签的y坐标:

library(ggplot2)
library(dplyr)

# 替换为你的真实数据集
df <- tibble(
  Type = rep(c("Rain", "Surface", "Stormwater"), each = 8),
  Chain = rep(c("Long Chain PFAS", "Short Chain PFAS"), each = 4, times = 3),
  Category = rep(c("Cat1", "Cat2", "Cat3", "Cat4"), times = 6),
  Value = sample(1:20, 24, replace = TRUE)
)

# 预处理:计算每个堆叠块的中心位置
df_processed <- df %>%
  group_by(Type, Chain) %>%
  mutate(
    total = sum(Value),
    prop = Value / total,
    y_end = cumsum(prop),
    y_start = y_end - prop,
    y_mid = (y_start + y_end) / 2  # 标签的中心定位点
  ) %>%
  ungroup()

绘图时用y_mid作为geom_text的y轴位置,标签就能精准居中:

p <- ggplot(df_processed, aes(x = interaction(Type, Chain), y = prop, fill = Category)) +
  geom_bar(stat = "identity", color = "white") +
  geom_text(aes(y = y_mid, label = sprintf("%.1f%%", prop*100)), 
            size = 3, color = "black") +
  coord_polar("y", start = 0) +
  theme_void()

2. 实现内圈两层非重复标签

单独构建标签数据,计算每个标签对应的角度中心,放在环形内圈(设置较小的y值):

第一步:构建第一层标签(Rain/Surface/Stormwater)

每个大类别对应2个柱子,取其角度范围的中心:

label_layer1 <- df_processed %>%
  distinct(Type, Chain) %>%
  group_by(Type) %>%
  summarise(
    x = mean(as.integer(interaction(Type, Chain))),
    y = -0.1  # 内圈位置,可根据环形大小调整
  )

第二步:构建第二层标签(长短链PFAS)

每个链类型对应自身柱子,直接取x的整数位置:

label_layer2 <- df_processed %>%
  distinct(Type, Chain) %>%
  mutate(
    x = as.integer(interaction(Type, Chain)),
    y = -0.2  # 比第一层更靠内,可调整
  )

第三步:添加到绘图中

用geom_text加入两层标签,隐藏原外侧x轴标签:

p +
  geom_text(data = label_layer1, aes(x = x, y = y, label = Type, group = NULL),
            size = 4, fontface = "bold", color = "darkgray") +
  geom_text(data = label_layer2, aes(x = x, y = y, label = Chain, group = NULL),
            size = 3, color = "gray") +
  theme(axis.text.x = element_blank())

关键注意事项

  • 替换模拟数据集为你的真实数据,确保分组逻辑和列名匹配
  • 内圈标签的y值可按需调整,负数绝对值越大越靠近中心
  • 若角度起始位置不符合预期,调整coord_polar的start参数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 11:04:51