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

使用R绘制分组条形图(dodged geom bar)遇到问题求助

解决R中分组条形图(dodged geom_bar)的问题

你的数据是宽格式,而ggplot2绘制分组条形图需要长格式数据,这是最常见的问题根源。下面是具体解决步骤:

1. 加载并清理数据

先把你提供的数据转为R数据框,同时清理部门名称里的多余空格:

# 创建数据框
df <- data.frame(
  Department = c("Admin Offices", "Executive Office", "IT/IS", "Production       ", "Sales", "Software Engineering"),
  Male = c(3, 0, 28, 83, 16, 5),
  Female = c(6, 1, 22, 126, 15, 6)
)
# 清理部门名称的多余空格
df$Department <- trimws(df$Department)

2. 转换数据格式为长格式

使用tidyr包的pivot_longer()函数,把宽格式数据转成ggplot2需要的长格式:

library(tidyr)
df_long <- pivot_longer(df, cols = c(Male, Female), names_to = "Gender", values_to = "Count")

3. 绘制分组条形图

用ggplot2生成并列式分组条形图:

library(ggplot2)
ggplot(df_long, aes(x = Department, y = Count, fill = Gender)) +
  geom_bar(stat = "identity", position = position_dodge()) +
  theme(axis.text.x = element_text(angle = 45, hjust = 1)) + # 旋转x轴标签避免重叠
  labs(title = "各部门员工性别分布", x = "部门", y = "人数")

关键注意点

  • position = position_dodge():这是实现分组条形图的核心参数,让不同性别的条形并列显示,而非堆叠。
  • 长格式数据要求:ggplot2需要把分类变量(性别)单独列为一列,才能通过fill参数区分分组。
  • 清理异常字符:原数据中"Production"后的多余空格会导致x轴标签显示异常,必须提前处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 09:46:39