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

ggplot2添加文本标签后饼图消失/压缩的原因及解决方法

问题:ggplot2分面饼图添加文本标签后压缩/消失

原因

你的代码里geom_bar用了position = position_fill(),这个参数会把每个分组的y值归一化到0-1的范围;但geom_text用的是position = position_stack(vjust = 0.5),这个是基于原始的Abundance数值(比如57.81、42.19这类)来堆叠位置。两者的坐标尺度不匹配,导致文本标签的位置超出了饼图的显示范围,ggplot自动调整了坐标轴,最终把饼图压缩甚至挤没了。

解决办法

把geom_text的位置参数改成和geom_bar一致的position_fill(vjust = 0.5),让文本标签的位置基于归一化后的y轴范围计算,就能和饼图匹配。

修改后的完整代码:

library(ggplot2)
library(viridis)
df <- data.frame('Fruit'=c("Apple", "Apple","Pear","Pear", "Coconut","Coconut"), 
                 'Colour'=c("Blue", "Yellow","Blue", "Yellow","Blue", "Yellow"), 
                 'Abundance'=c(57.81,42.19,59.89,40.11,41.73,58.27))

ggplot(df, aes(x = "", y = Abundance, fill = Colour)) + 
  geom_bar(stat = "identity", width = 1, position = position_fill(), colour="black") +
  coord_polar(theta = "y")+
  facet_wrap(~ Fruit, ncol=3)+
  theme_void() +
  scale_fill_viridis(discrete= TRUE)+
  geom_text(aes(label = ifelse(Abundance == 0, "", paste0(Abundance, "%"))),
            position = position_fill(vjust = 0.5))

效果对比

添加标签前的饼图:
添加标签前的饼图

修复后添加标签的饼图:
(将显示结构与原图一致、带有百分比标签的正常分面饼图)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 15:53:29