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

如何在ggplot2中绘制仅显示Yes类别百分比且居中的多面饼图

解决方案:让饼图中心显示Yes类别的百分比

问题背景

需要用ggplot2绘制分面饼图,每个饼图展示"Yes"和"No"的占比,仅显示"Yes"的百分比,且该百分比要在整个饼图的中心位置,而非仅在"Yes"切片内居中。

数据集

df <- data.frame(Perc = c(78, 94, 99, 22, 6, 1), 
    Source = as.factor(rep(c("Oil", "Solar", "Wind"), 2)),
    Agree = as.factor(c(rep("Yes", 3), rep("No", 3))))

修改后的代码

# 提取仅包含Yes的数据,用于中心文本标注
df_yes <- subset(df, Agree == "Yes")

ggplot(df, aes(x=" ", y=Perc, group=rev(Agree), fill=Agree)) +
    geom_bar(size = .5, stat = "identity", color = "black") + 
    scale_fill_manual(values = c("grey", "lightgreen")) +
    coord_polar("y", start=0) + 
    # 使用单独的Yes数据集,固定y=50(饼图总占比100,50对应中心)
    geom_text(data = df_yes, aes(label = paste0(Perc, "%")), y = 50, size = 5) +
    facet_grid(~Source) + 
    theme_void() + 
    theme(legend.position = "none", strip.text.x = element_text(size = 9))

关键说明

  • 原代码中geom_text绑定在原始数据集上,文本位置默认对应切片的中间位置(即y = Perc/2),所以只会在Yes切片内居中。
  • 单独提取Yes类别的数据集后,设置y = 50(因为饼图的y轴总和为100,50正好是整个饼图的中心位置),就能让文本固定在饼图正中心。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 04:40:28