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

使用ggplot绘制多分组变量条形图并调整分组颜色求助

用ggplot绘制目标样式的堆叠条形图

我想在R中用ggplot创建堆叠条形图,样式参考以下两种(优先第二种):

  • 样式1:分组堆叠条形图,不同类别分组展示
  • 样式2:以年份为横轴的堆叠条形图,每个年份的条形由不同类别堆叠而成

样本数据

df <- data.frame(
  year = c(1988,1989,1990,1991,1992,1993,1994,1995,1996,1997,
           1998,1999,2000,2001,2002,2003,2004,2005,2006,2007,
           2008,2009,2010,2011,2012,2013,2014,2015,2016,2017,
           2018,2019,2020,2021,2022),
  LS4 = c(0,5,0,0,0,0,0,0,0,0,
          0,0,0,0,0,0,0,0,0,0,
          0,0,0,0,0,0,0,0,0,0,
          0,0,0,0,0),
  LS5 = c(35,45,37,29,23,32,46,35,47,40,
          52,55,46,38,0,6,47,41,45,43,
          42,49,29,25,0,0,0,0,0,0,
          0,0,0,0,0),
  LS7 = c(0,0,0,0,0,0,0,0,0,0,
          0,3,20,24,43,33,42,27,25,26,
          26,38,23,23,28,34,50,56,49,52,
          51,57,54,48,49),
  LS8 = c(0,0,0,0,0,0,0,0,0,0,
          0,0,0,0,0,0,0,0,0,0,
          0,0,0,0,0,33,60,61,58,53,
          58,60,55,53,49),
  LS9 = c(0,0,0,0,0,0,0,0,0,0,
          0,0,0,0,0,0,0,0,0,0,
          0,0,0,0,0,0,0,0,0,0,
          0,0,0,6,52),
  obs = c(35,50,37,29,23,32,46,35,47,40,
          52,58,66,62,43,39,89,68,70,69,
          68,87,52,48,28,67,110,117,107,105,
          109,117,109,107,150))

尝试的代码

barplot1 <- data %>%
  ggplot(aes(x=year, y=obs, fill=interaction(LS4,LS5,LS7,LS8,LS9))) +
  geom_bar(stat="identity", position=position_dodge()) +
  scale_color_manual(values = c("blue", "cyan", "red", "orange"))
barplot1

当前生成的图不符合预期,需要调整代码实现目标样式。


解决方案

关键问题分析

原代码的问题在于:

  1. 使用宽格式数据,ggplot绘制堆叠图需要长格式数据
  2. 用interaction(LS4,LS5,...)作为填充分组,会生成大量无意义组合,导致颜色混乱
  3. 错误使用scale_color_manual,应该用scale_fill_manual控制填充色

修正步骤

  1. 将宽格式数据转换为长格式,保留year和各LS系列的数值
  2. 过滤掉数值为0的行,避免堆叠无效部分
  3. 用geom_col(等价于geom_bar(stat="identity"))绘制堆叠条形图
  4. 自定义填充色,添加标签和主题优化

完整代码

library(tidyverse)

# 转换为长格式并过滤0值
df_long <- df %>%
  select(-obs) %>%  # 去掉obs列,因为LS系列的和就是obs
  pivot_longer(cols = starts_with("LS"), names_to = "sensor", values_to = "count") %>%
  filter(count > 0)

# 绘制堆叠条形图(对应样式2)
ggplot(df_long, aes(x = year, y = count, fill = sensor)) +
  geom_col() +
  # 自定义填充色,可根据需求调整
  scale_fill_manual(values = c("LS4" = "blue", "LS5" = "cyan", "LS7" = "red", "LS8" = "orange", "LS9" = "darkgreen")) +
  labs(title = "各传感器年度观测数量堆叠图",
       x = "年份",
       y = "观测数量",
       fill = "传感器类型") +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))  # 旋转年份标签避免重叠

效果说明

这段代码会生成以年份为横轴的堆叠条形图,每个年份的条形由对应有观测值的传感器类别堆叠而成,和你想要的第二种样式一致。如果需要类似第一种分组样式,只需调整x轴为传感器类型,fill为年份即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 23:35:18