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

如何修正因子转换错误并使用ggplot绘制熟悉度评分饼图

问题修正与饼图绘制方案

错误原因

你的因子转换代码报错是因为levels = 1:5与原数据中Q5_Know_Familirity_ogd_Concept列的实际值(中文类别:完全不熟悉、略微熟悉、中等熟悉、非常熟悉、极度熟悉)不匹配,导致无法完成标签映射,最终生成NA值。

修正后的数据处理代码

将因子的levels参数替换为原数据中的中文类别,确保与实际值完全对应,即可完成英文标签的转换:

library(dplyr)

F_ogd_data_new <- ogd_data_new %>%
  select(Q5_Know_Familirity_ogd_Concept) %>%
  group_by(Q5_Know_Familirity_ogd_Concept) %>%
  summarise(Frequency = n()) %>% 
  mutate(Percent = round(Frequency/sum(Frequency)*100, 1)) %>%
  mutate(Q5_Know_Familirity_ogd_Concept = factor(Q5_Know_Familirity_ogd_Concept, 
                           levels = c("完全不熟悉", "略微熟悉", "中等熟悉", "非常熟悉", "极度熟悉"),
                           labels = c("Not at all familiar",
                                      "Slightly familiar", 
                                      "Moderately familiar", 
                                      "Very familiar", 
                                      "Extremely familiar"))) %>%
  filter(!is.na(Q5_Know_Familirity_ogd_Concept)) # 移除未匹配的无效类别

ggplot绘制目标饼图代码

以下代码可生成带百分比标签、分类清晰的饼图,匹配你预期的效果:

library(ggplot2)

ggplot(F_ogd_data_new, aes(x = "", y = Percent, fill = Q5_Know_Familirity_ogd_Concept)) +
  # 绘制基础条形图(后续转为饼图)
  geom_bar(stat = "identity", width = 1) +
  # 转换为饼图坐标系
  coord_polar("y", start = 0) +
  # 添加百分比标签,居中显示在扇区内
  geom_text(aes(label = paste0(Percent, "%")), position = position_stack(vjust = 0.5)) +
  # 设置配色方案(可根据需求调整)
  scale_fill_brewer(palette = "Set3") +
  # 移除冗余的坐标轴元素
  theme_void() +
  # 设置标题与图例名称
  labs(title = "Familiarity with OGD Concept",
       fill = "Familiarity Level")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 08:52:38