求助:R语言绘制分组柱状图(按Pillar统计颜色频次)及gather报错
解决方法
首先,你的gather函数参数错误是导致报错的核心原因,以下是完整的修正步骤:
1. 修正长格式转换代码
gather函数的正确语法是gather(data, key列名, value列名, 要转换的列范围),你缺少了value列的定义,导致参数解析失败。推荐使用tidyr新版的pivot_longer函数(语法更清晰,避免参数顺序混淆):
# 加载必要包 library(tidyr) library(dplyr) # 转换为长格式:measure存储Budget/Schedule等主题,status存储green/yellow/red状态 projects_long <- pivot_longer(projects_sum, cols = Budget:Ressources, names_to = "measure", values_to = "status")
如果坚持用旧版gather,修正后的代码是:
projects_long <- gather(projects_sum, key = measure, value = status, Budget:Ressources)
2. 统计各分组的状态次数
用dplyr按Pillar、measure、status分组计数:
projects_count <- projects_long %>% group_by(Pillar, measure, status) %>% count() %>% ungroup()
3. 绘制按Pillar分组的柱状图
用ggplot2生成并列柱状图,按Pillar分面展示:
library(ggplot2) ggplot(projects_count, aes(x = measure, y = n, fill = status)) + geom_col(position = "dodge") + # 并列显示同主题的不同状态 facet_wrap(~Pillar) + # 按Pillar分组展示子图 scale_fill_manual(values = c("green" = "#00A651", "yellow" = "#FFCC00", "red" = "#E63946")) + labs(x = "主题", y = "次数", fill = "状态", title = "各Pillar下主题状态分布") + theme_bw()
内容的提问来源于stack exchange,提问作者user21699241
相关产品推荐
相关产品推荐

