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

在ggplot条形图中实现等宽柱形与紧凑X轴

解决方法

核心问题是你补全了所有class/var_1的缺失组合(包括NA值),导致每个class分组下都预留了所有var_1的位置,从而产生空白。要在不增加柱宽的前提下消除空白,可按以下步骤调整:

步骤1:移除补全缺失组合的代码

删掉代码中用rbind补全NA行的部分,保留原始的tmpdf:

library(tibble)
library(ggplot2)

tmpdf <- tibble(class = c("class 1", rep("class 2", 4), rep("class 3", 4)),
                var_1 = c("none", rep(c("A", "B", "C", "D"), 2)),
                y_ = as.integer(c(runif(9, min = 100, max=250))))

步骤2:调整position_dodge的参数

使用position_dodge(preserve = "single")替代原来的position_dodge(width = 0.90),这个参数会让每个分组内的柱子保持相同宽度,同时自动消除缺失组合带来的空白:

ggplot(data=tmpdf, aes(x = class, y = y_, fill=var_1, width=0.75 )) +
  geom_bar(stat = "identity", position=position_dodge(preserve = "single"), color="black", size=0.2)

原理说明

preserve = "single"会让ggplot根据每个分组内实际存在的柱子数量分配空间,而非按所有分组中最多的柱子数量预留位置。这样class 1下只有1个柱子时,不会为不存在的A/B/C/D预留空白,同时所有柱子的宽度保持一致,满足你的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 08:45:29