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

在R中用ggplot2绘制饼图:为何仅显示单一颜色而非F、M双色?

问题原因及解决方法

你的代码里**fill="Sesso"和y='Percentage'**用了引号,这会让ggplot把它们当成固定的字符串常量,而非数据框里的变量。fill被设成单一值"Sesso",自然只会显示一种颜色;y也没正确关联到Percentage列的数据。

修正后的代码
setable<-structure(list(Sesso = structure(1:2, levels = c("F", "M"), class = "factor"), 
    Percentage = c(47732L, 36754L)), class = "data.frame", row.names = c(NA, 
-2L))

library(ggplot2)
# 去掉y和fill的引号,正确映射变量
bp <- ggplot(setable, aes(x="", y=Percentage, fill=Sesso)) +
  geom_bar(width = 1, stat = "identity")
pie <- bp + coord_polar("y", start=0)
pie
可选优化(让饼图更清晰)

如果需要显示占比标签、简化样式,可以添加以下代码:

pie + 
  geom_text(aes(label = paste0(round(Percentage/sum(Percentage)*100, 1), "%")), 
            position = position_stack(vjust = 0.5)) +
  theme_void() # 移除多余的坐标轴和背景元素

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 17:27:07