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

如何用R绘制含重复值单变量的饼图(带数值与百分比)

解决ggplot绘制饼图的问题

原代码的问题点

  • 包名错误:应该加载ggplot2而非ggplot
  • 数据重复:原数据框每个类别重复了两次,直接绘图会导致切片大小翻倍
  • 数据类型错误:answer_type_count是字符型,无法正确参与数值计算

完整解决代码

第一步:处理数据(去重+类型转换+计算标签)

# 加载正确的绘图包
library(ggplot2)

# 原数据
df <- data.frame(answer_type_count= rep(c("6","46", "3"),2),
                 answer_type= rep(c("correct", "wrong","no answer"),2))

# 去重并将计数列转为数值型
df_clean <- unique(df)
df_clean$answer_type_count <- as.numeric(df_clean$answer_type_count)

# 计算百分比并生成标签(数值+百分比)
total <- sum(df_clean$answer_type_count)
df_clean$percentage <- round((df_clean$answer_type_count / total)*100, 1)
df_clean$label <- paste0(df_clean$answer_type_count, " (", df_clean$percentage, "%)")

第二步:绘制带标签的饼图

ggplot(df_clean, aes(x = "", y = answer_type_count, fill = answer_type)) +
  geom_bar(stat = "identity", width = 1) + # width=1保证饼图规整
  coord_polar("y", start = 0) +
  # 将标签放在切片中间位置
  geom_text(aes(label = label), position = position_stack(vjust = 0.5)) +
  # 去掉冗余的坐标轴、网格线
  theme_void() +
  # 可选添加标题
  labs(title = "答题类型分布")

代码说明

  • unique(df)直接去除重复行,确保每个类别只统计一次
  • 转换计数列为数值型后,ggplot才能正确计算各切片的占比
  • geom_text搭配position_stack(vjust=0.5)让标签精准落在切片中心
  • theme_void()精简了图表元素,让饼图更美观清晰

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 23:46:05