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

如何用ggplot2绘制带分面的分组堆叠条形图展示时间占比

我来帮你搞定这个堆叠条形图的问题!你现在的代码是把prep_time和operation_time直接合并成一个整体,所以没法区分两者的占比。要实现堆叠显示并添加图例,核心是把数据从宽格式转换成长格式,让ggplot能识别不同的时间类型。

完整解决方案代码

# 加载必要的包
library(ggplot2)
library(tidyr) # 用于数据格式重塑

# 读取数据
df <- read.csv("test.csv", strip.white = TRUE)

# 将宽格式数据转换为长格式
df_long <- pivot_longer(df, 
                        cols = c(prep_time, operation_time), # 指定要转换的时间列
                        names_to = "time_category", # 新的分类列名(区分准备/操作时间)
                        values_to = "time_value") # 对应的时间数值列名

# 绘制堆叠条形图
plot <- ggplot(df_long, aes(x = system, y = time_value, fill = time_category)) +
  geom_bar(stat = "identity") + # 堆叠模式,直接使用y轴数值
  facet_grid(. ~ operation_type) + # 按operation_type分面展示
  labs(title = "Total Time Breakdown by System & Operation Type",
       x = "System",
       y = "Time (units)",
       fill = "Time Type") + # 自定义图例、坐标轴和标题文本
  theme_minimal() # 可选:使用简洁主题美化图表

# 输出图表
print(plot)

关键步骤解释

  1. 数据格式转换:
    pivot_longer函数把原来的两列时间数据(prep_time和operation_time)重塑成两列:

    • time_category:标记当前数值属于"准备时间"还是"操作时间"
    • time_value:对应具体的时间数值
      这样ggplot就能通过fill = time_category参数区分不同部分,自动生成堆叠效果和图例。
  2. 堆叠条形图设置:
    geom_bar(stat = "identity")表示直接使用y轴的数值(而不是默认的计数),配合fill参数就能实现堆叠显示不同时间类型的占比。

  3. 美化与自定义:
    通过labs可以修改图表的标题、坐标轴标签和图例名称,theme_minimal是可选的美化主题,你也可以换成theme_bw()或其他自定义样式。

替代方案(无tidyr包时)

如果你的环境没有安装tidyr包,可以用base R的reshape函数完成格式转换:

df_long <- reshape(df, 
                   varying = c("prep_time", "operation_time"),
                   v.names = "time_value",
                   timevar = "time_category",
                   times = c("prep_time", "operation_time"),
                   direction = "long")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:34:59