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

如何用ggplot实现堆叠与并列混合的柱状图(非数值X轴)

解决方案

要实现「Bidrag与Depot堆叠、同时和GaranteretYdelse并列」的效果,需要先调整数据结构新增分组变量,再通过ggplot的分组与位置参数实现组合布局:

步骤1:调整数据结构

在长格式数据中新增DodgeGroup变量,将Bidrag和Depot归为同一堆叠组,GaranteretYdelse设为独立组:

produkt_A_data_long <- produkt_A_data %>%
  tidyr::pivot_longer(cols = -Grundlag, names_to = "Attribute", values_to = "Value") %>%
  # 定义分组规则:Bidrag和Depot属于堆叠组,其余为独立组
  mutate(DodgeGroup = case_when(
    Attribute %in% c("Bidrag", "Depot") ~ "Stacked",
    TRUE ~ "Standalone"
  ))

步骤2:绘制组合柱状图

通过group参数指定分组逻辑,使用position_dodge2()实现「组内堆叠、组间并列」的效果,preserve = "single"确保不同组的柱子宽度一致:

ggplot(produkt_A_data_long, aes(x = Grundlag, y = Value, fill = Attribute, group = interaction(DodgeGroup, Attribute))) +
  geom_bar(stat = "identity", 
           position = position_dodge2(width = 0.9, preserve = "single")) +
  labs(title = "Aggregated Values by Grundlag",
       x = "Grundlag",
       y = "Value",
       fill = "Attribute") +
  theme_minimal()

可选调整

若要改变堆叠顺序,可通过factor()指定Attribute的层级,层级靠前的元素会被堆叠在下方:

# 示例:让Depot在下方,Bidrag在上方
produkt_A_data_long$Attribute <- factor(produkt_A_data_long$Attribute, levels = c("Depot", "Bidrag", "GaranteretYdelse"))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 20:13:14