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

R语言饼图标签调整:解决标签拥挤重叠问题

饼图标签重叠问题的解决方法

你的数据中DIESEL/ELECTRIC占比仅约0.07%,四舍五入后显示为0%,这类极小占比的类别是导致标签拥挤重叠的核心原因。以下是几种可行的解决思路:

方法1:优化基础pie函数的标签设置

可以通过换行标签、针对小类别调整字号,或者手动指定标签位置来缓解重叠:

pct <- round(100*fuel_trend$no_car_21/sum(fuel_trend$no_car_21))
# 给标签添加换行,避免单行过长
labels <- paste(fuel_trend$fuel_type, pct, "%", sep = "\n")
# 给占比<1%的类别单独缩小字号
cex_vals <- ifelse(pct < 1, 0.5, 0.8)

pie(fuel_trend$no_car_21, 
    labels = labels, 
    cex = cex_vals)

也可以手动调整小类别标签到饼图外部:

# 计算每个饼块的中点角度
angles <- (cumsum(fuel_trend$no_car_21) - 0.5*fuel_trend$no_car_21)/sum(fuel_trend$no_car_21)*360
# 小占比标签移到外部(pos=2),其余留在内部(pos=1)
pos_vals <- ifelse(pct < 1, 2, 1)

pie(fuel_trend$no_car_21, 
    labels = labels, 
    cex = cex_vals,
    pos = pos_vals,
    angle = angles)

方法2:使用ggplot2绘制(更推荐)

ggplot2对标签布局的控制更灵活,能自动优化位置,甚至借助第三方包实现智能避障:

library(ggplot2)
# 先计算占比并生成标签
fuel_trend$pct <- round(100*fuel_trend$no_car_21/sum(fuel_trend$no_car_21), 2)
fuel_trend$label <- paste(fuel_trend$fuel_type, fuel_trend$pct, "%", sep = "\n")

# 基础饼图
ggplot(fuel_trend, aes(x = "", y = no_car_21, fill = fuel_type)) +
  geom_col(width = 1) +
  coord_polar("y", start = 0) +
  geom_text(aes(label = label), position = position_stack(vjust = 0.5), size = 3) +
  theme_void() # 清理冗余元素

如果仍有重叠,用ggrepel包的geom_text_repel自动调整标签位置:

library(ggrepel)
ggplot(fuel_trend, aes(x = "", y = no_car_21, fill = fuel_type)) +
  geom_col(width = 1) +
  coord_polar("y", start = 0) +
  geom_text_repel(aes(label = label), position = position_stack(vjust = 0.5), size = 3) +
  theme_void()

方法3:合并极小占比类别

将占比低于阈值的类别合并为“其他”,从根源上减少标签数量:

threshold <- 1 # 设定占比阈值为1%
fuel_trend$pct <- round(100*fuel_trend$no_car_21/sum(fuel_trend$no_car_21), 2)
# 生成合并后的类别
fuel_trend$fuel_type_combined <- ifelse(fuel_trend$pct < threshold, "OTHER", fuel_trend$fuel_type)
# 重新汇总数据
fuel_trend_combined <- aggregate(no_car_21 ~ fuel_type_combined, data = fuel_trend, sum)
fuel_trend_combined$pct <- round(100*fuel_trend_combined$no_car_21/sum(fuel_trend_combined$no_car_21), 2)
fuel_trend_combined$label <- paste(fuel_trend_combined$fuel_type_combined, fuel_trend_combined$pct, "%", sep = "\n")

# 绘制饼图
pie(fuel_trend_combined$no_car_21, labels = fuel_trend_combined$label, cex = 0.8)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 11:40:24