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

如何在ggplot中将重叠的两组柱状图的柱子并列显示?

解决ggplot柱状图重叠问题的方案

你的问题核心是用了两个独立的geom_bar分别对应不同变量,导致ggplot无法识别它们属于同一分组的对比项,从而出现重叠。正确的做法是先把数据转换为长格式,再用单个geom_bar配合position_dodge实现并列。

步骤1:转换数据格式

首先用tidyr包把宽格式数据转成长格式(如果没安装该包,先运行install.packages("tidyr")):

library(tidyr)
library(ggplot2)

# 将两个年龄分组变量合并为一列,同时标记变量类型
Graph_long <- pivot_longer(Graph, 
                           cols = c(AgeFactor, FdgFactor),  # 指定要合并的两列
                           names_to = "Variable",           # 新列:标记是诊断年龄还是喂养问题年龄
                           values_to = "AgeGroup")          # 新列:统一存放年龄分组

# 可选:如果数据里有缺失值,可去掉
# Graph_long <- Graph_long %>% drop_na()

步骤2:修正ggplot代码

用转换后的长格式数据绘图,通过fill区分两个变量,并用position_dodge让柱子并列:

Labeled <- ggplot(Graph_long, aes(x = AgeGroup, fill = Variable)) +
  ggtitle("Figure 1. Comparison of Distribution of Age of Diagnosis and Age of Feeding Challenges") +
  geom_bar(position = position_dodge(width = 0.8),  # 设置并列宽度
           alpha = 0.5, 
           width = 0.7) +  # 单个柱子的宽度
  scale_x_discrete(limits = c("0-6months","7-12months","1-1.99","2-2.99","3-3.99","4-4.99","5-5.99","6-6.99","7-7.99","8-8.99","9-9.99","10-10.99")) +
  xlab("Age") +
  ylab("") +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) +
  scale_fill_discrete(name = "", 
                      labels = c("Age of Autism Diagnosis", "Feeding Challenge Onset"))  # 自定义图例标签

关键说明

  • 长格式数据把原本分散的两个变量整合到同一结构中,让ggplot能识别哪些柱子属于同一年龄组的对比项。
  • position_dodge(width = 0.8)控制并列柱子的间距,width = 0.7控制单个柱子的宽度,可根据需求调整数值。

内容的提问来源于stack exchange,提问作者Brittany St. John

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 02:15:36