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

ggplot2:如何消除水平堆叠条形图的多余垂直空白?

解决ggplot2水平堆叠条形图多余垂直空白问题

你的问题主要来自三个点:过窄的条形宽度、coord_fixed与coord_flip的顺序冲突,以及离散坐标轴的默认边距。以下是针对性的解决方案:

核心修改方案

1. 增大条形宽度+移除冗余边距

把geom_bar的width从0.1调至合适值(比如0.8),同时关闭离散坐标轴的默认扩展边距,这是减少垂直空白最直接的方法:

ggplot(category_df, aes(x = OPERATION, y = CATEGORY_LOT_COUNT, fill=HOLD_CATEGORY, label=CATEGORY_LOT_COUNT)) +
  geom_bar(position="stack", stat="identity", width=0.8) +  # 加宽条形,减少上下空白
  xlab("") +
  scale_x_discrete(expand = c(0, 0)) +  # 移除离散轴两端的默认空白
  theme(axis.title.x = element_blank(),
        axis.ticks.x=element_blank(),
        axis.text.x=element_blank(),
        legend.title.align = 0.5,
        legend.direction = 'horizontal',
        legend.position = 'bottom',
        plot.margin = margin(5, 10, 5, 10)) +  # 可选:微调图表整体边距
  geom_text(position = position_stack(vjust = 0.5), size=10, color='white', face = 'bold') +
  coord_flip()

2. 若需固定比例,调整coord_fixed顺序

如果必须保持坐标轴比例,要先执行coord_flip再设置coord_fixed,因为翻转后坐标轴的对应关系会变化,比例参数需要重新适配:

ggplot(category_df, aes(x = OPERATION, y = CATEGORY_LOT_COUNT, fill=HOLD_CATEGORY, label=CATEGORY_LOT_COUNT)) +
  geom_bar(position="stack", stat="identity", width=0.8) +
  xlab("") +
  scale_x_discrete(expand = c(0, 0)) +
  theme(axis.title.x = element_blank(),
        axis.ticks.x=element_blank(),
        axis.text.x=element_blank(),
        legend.title.align = 0.5,
        legend.direction = 'horizontal',
        legend.position = 'bottom') +
  geom_text(position = position_stack(vjust = 0.5), size=10, color='white', face = 'bold') +
  coord_flip() +
  coord_fixed(ratio = 0.05)  # 根据图表实际大小调整比例,值越小垂直空白越少

原因说明

  • width=0.1会让条形极度狭窄,ggplot为离散型x轴(翻转后变为y轴)自动预留大量间隔空间,导致垂直空白过多;
  • coord_fixed和coord_flip的顺序会影响比例计算,先翻转再设置比例才能正确对应翻转后的坐标轴;
  • scale_x_discrete(expand = c(0,0))直接关闭了离散轴两端的默认扩展边距,这是消除冗余空白的关键设置。

内容的提问来源于stack exchange,提问作者rchitect-of-info

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 08:05:20