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

求助: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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 16:22:26