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

如何使用ggplot正确放置饼图标签 解决小占比标签重叠问题

解决方案

核心问题说明

你之前的代码调用geom_text_repel不生效,是因为极坐标场景下position_stack的定位逻辑和ggrepel的位置计算逻辑冲突,无法正确识别每个小占比标签的初始位置,也就没法生成引导线和自动排布。

完整可运行代码

library(tidyverse)
library(ggrepel)

# 构造数据并预计算标签位置
df <- tibble(
  n = c(1, 1, 1, 2, 50, 46),
  label = paste0(c(1, 1, 1, 2, 50, 46), "%")
) %>% 
  mutate(
    # 计算每个分类的累积区间和中点,用于标签初始定位
    cum_y = cumsum(n),
    mid_y = cum_y - n/2,
    # 计算标签旋转角度,避免文字倒过来
    angle = 90 - 360 * mid_y / sum(n),
    angle = ifelse(angle < -90, angle + 180, angle)
  )

# 绘图
ggplot(df, aes(x = 1, y = n)) +
  geom_bar(width = 1, stat = "identity", fill = c("#f8766d", "#c77cff", "#00bfc4", "#7cae00", "#ffa500", "#00b0f6"), color = "white") +
  geom_text_repel(
    aes(y = mid_y, label = label, angle = angle),
    segment.size = 0.3,
    segment.color = "grey50",
    # 如需箭头可取消下一行注释
    # arrow = arrow(length = unit(0.02, "npc")),
    nudge_x = 0.8,
    size = 3.5,
    direction = "y",
    force = 10
  ) +
  coord_polar("y", start = 0) +
  xlim(0.5, 2.5) +
  theme_void() +
  theme(legend.position = "none")

参数说明

  • direction = "y":限制标签仅沿纵向调整位置,避免引导线杂乱交叉
  • force:调整标签之间的排斥力,数值越大标签间距越大,可根据实际数据量调整
  • nudge_x:控制标签和饼图边缘的距离,数值越大标签越靠外
  • 开启arrow参数即可为引导线添加箭头效果

运行上述代码即可得到标签无重叠、带引导线的饼图效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 13:36:08