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

如何在ggplot中固定多列来源堆叠条形图的层级顺序

固定堆叠条形图层级顺序的解决方案

问题背景

现有如下R数据框,需要创建堆叠条形图:

  • X轴为serial_number
  • Y轴基于sensor_1至sensor_5的数值,要求sensor_1在最底层,sensor_2堆叠于其上,依此类推至sensor_5
  • 每个sensor层的填充颜色对应同名的error_codes列(如sensor_1对应error_codes1)

原代码通过多次调用geom_bar尝试实现,但无法固定堆叠层级顺序:

df <- data.frame(
  datetime = as.POSIXct(c("2022-11-15 04:06:30", "2022-11-16 04:06:43", "2022-11-17 06:27:57", "2022-11-17 11:07:18")),
  serial_number = c("2097210", "2097203", "2106093", "2097208"),
  sensor_1 = c(0.03, 0.050288, 0.131424, 0.050692),
  sensor_2 = c(0.02, 0.04463, 0.018534, 0.038841),
  sensor_3 = c(0.024268, 0.039078, 0.011794, 0.020183),
  sensor_4 = c(0.011116, 0.024343, 0.009267, 0.016428),
  sensor_5 = c(0.004697, 0.017083, 0.009267, 0.007393),
  error_codes1 = c("F4", "F3","F2","F4"),
  error_codes2 = c("F4", "F3","F2","F4"),
  error_codes3 = c("F2", "F1","F3","F8"),
  error_codes4 = c("F4", "F7","F3","F1"),
  error_codes5 = c("F2", "F6","F1","F4")
)

# 原代码
ggplot(df, aes(x=serial_number)) +
  geom_bar(aes(y=sensor_1, fill=error_codes1), position = "stack", stat = "identity") +
  geom_bar(aes(y=sensor_2, fill=error_codes2), position = "stack", stat = "identity") +
  geom_bar(aes(y=sensor_3, fill=error_codes3), position = "stack", stat = "identity") +
  geom_bar(aes(y=sensor_4, fill=error_codes4), position = "stack", stat = "identity") +
  geom_bar(aes(y=sensor_5, fill=error_codes5), position = "stack", stat = "identity") 

核心原因

多次调用geom_bar时,position="stack"仅对当前图层内的元素生效,而非在之前图层的基础上累加,导致层级顺序混乱。正确的做法是将数据转换为长格式,统一控制堆叠逻辑。

解决方案

  1. 加载tidyverse包(用于数据整理和绘图)
  2. 将宽格式数据转换为长格式,绑定每个sensor对应的error_code,并指定层级顺序
  3. 用单个geom_bar绘制堆叠条形图,通过因子顺序固定层级

完整代码如下:

library(tidyverse)

# 转换为长格式数据
df_long <- df %>%
  select(serial_number, starts_with("sensor_"), starts_with("error_codes")) %>%
  pivot_longer(
    cols = -serial_number,
    names_to = c(".value", "level"),
    names_pattern = "(sensor|error_codes)_(\\d)"
  ) %>%
  rename(sensor_value = sensor, error_code = error_codes) %>%
  # 固定层级顺序:sensor_1在最底层
  mutate(level = factor(paste0("sensor_", level), levels = paste0("sensor_", 1:5)))

# 绘制堆叠条形图
ggplot(df_long, aes(x = serial_number, y = sensor_value, fill = error_code)) +
  geom_bar(aes(group = level, order = level), position = "stack", stat = "identity") +
  labs(y = "Sensor Value", fill = "Error Code") +
  theme_minimal()

代码说明

  • pivot_longer通过正则表达式将sensor_1与error_codes1配对,生成包含层级标识的长格式数据
  • mutate将level转换为因子并指定顺序,确保sensor_1到sensor_5的堆叠顺序固定
  • aes(group = level, order = level)强制ggplot按照指定的层级顺序堆叠,避免顺序混乱

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 07:13:25