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

ggplot堆叠条形图:调整方向、设置嵌套Y轴标签及显示条形数值

解决方案

要实现Sales在X轴,Year与Category在Y轴区域的水平堆叠条形图,并显示每个堆叠块的销售数值,可通过两种方式调整:

方式1:合并Year与Category为Y轴变量

直接将Year和Category组合成单个Y轴分类变量,无需分面,直观展示两者的组合关系:

library(ggplot2)

data2 <- read.table(text = "Product Category Year Sales
               A Clothing 2017 100
               A Clothing 2018 120
               A Electronics 2017 150
               A Electronics 2018 200
               A Food 2017 50
               A Food 2018 80
               B Clothing 2017 80
               B Clothing 2018 90
               B Electronics 2017 100
               B Electronics 2018 120
               B Food 2017 70
               B Food 2018 100", header=TRUE)

# 生成Year+Category的组合Y轴变量
data2$Y_label <- paste(data2$Year, data2$Category, sep = " - ")

# 绘制水平堆叠条形图
ggplot(data2, aes(y = Y_label, x = Sales, fill = Product)) +
  geom_bar(stat = "identity", position = "stack") +
  # 添加居中的销售数值标签
  geom_text(aes(label = Sales), position = position_stack(vjust = 0.5), size = 3) +
  labs(x = "Sales", y = "Year - Category") +
  theme(
    panel.background = element_rect(fill = "white", colour = "white"),
    axis.line = element_line(colour = "grey"),
    panel.grid.major.x = element_line(colour = "grey")
  )

方式2:用分面调整Category到Y轴区域

如果需要保留Year和Category的独立展示,可使用facet_grid替代facet_wrap,并通过switch="y"将Category标签移到Y轴左侧,配合coord_flip实现需求:

library(ggplot2)

data2 <- read.table(text = "Product Category Year Sales
               A Clothing 2017 100
               A Clothing 2018 120
               A Electronics 2017 150
               A Electronics 2018 200
               A Food 2017 50
               A Food 2018 80
               B Clothing 2017 80
               B Clothing 2018 90
               B Electronics 2017 100
               B Electronics 2018 120
               B Food 2017 70
               B Food 2018 100", header=TRUE)

ggplot(data2, aes(x = Year, y = Sales, fill = Product)) +
  geom_bar(stat = "identity") +
  geom_text(aes(label = Sales), position = position_stack(vjust = 0.5), size = 3) +
  # 将Category作为行分面,并把标签切换到Y轴左侧
  facet_grid(Category ~ ., switch = "y") +
  coord_flip() +
  labs(y = "Sales", x = "") +
  theme(
    panel.spacing = unit(0, "lines"),
    strip.background = element_blank(),
    axis.line = element_line(colour = "grey"),
    panel.grid.major.x = element_line(colour = "grey"),
    strip.placement = "outside",
    panel.background = element_rect(fill = "white", colour = "white")
  )

原代码问题说明

你之前使用facet_wrap(vars(Category), strip.position = "bottom")配合coord_flip时,strip会被翻转到图表右侧,而非Y轴区域。改用facet_grid并设置switch="y",能让Category标签直接与Year的Y轴刻度对齐,满足需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 15:05:12