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

使用facet_wrap时如何让ggplot柱状图实现并列显示而非堆叠

解决ggplot柱状图并列(非堆叠)的问题

你当前代码里的position = "dodge"参数位置错误,导致柱状图始终处于堆叠状态,以下是问题说明和修正方案:

原问题代码

library(pacman)
#> Warning: package 'pacman' was built under R version 4.2.1
p_load(tidyverse)
titanic = read.csv("https://code.datasciencedojo.com/datasciencedojo/tutorials/raw/master/Datasets/titanic.csv")
titanic$survived_label = ifelse(titanic$Survived == 0, "Survived",
                                "Dead")

titanic = titanic %>% mutate(family_size = 1 + SibSp + Parch)

titanic %>% group_by(Sex, survived_label, Pclass) %>% 
  summarise(mean = mean(family_size)) %>% 
  ggplot(aes(Sex, mean, fill = factor(Pclass), 
             group = factor(survived_label)), position = "dodge"
         ) + 
  geom_col() + facet_wrap(~ survived_label)
#> `summarise()` has grouped output by 'Sex', 'survived_label'. You can override
#> using the `.groups` argument.

原图表(堆叠状态):
堆叠状态的柱状图

修正方案

  1. 调整position = "dodge"的位置:该参数属于geom_col()的控制参数,需要放在geom_col()内,而非ggplot()的外层参数中。
  2. 修正group参数:由于已经通过facet_wrap按survived_label分面,同个分面内需要按Pclass分组,才能让不同舱位的柱子并列显示,因此将group设置为factor(Pclass)。

修正后的代码:

library(pacman)
p_load(tidyverse)
titanic = read.csv("https://code.datasciencedojo.com/datasciencedojo/tutorials/raw/master/Datasets/titanic.csv")
titanic$survived_label = ifelse(titanic$Survived == 0, "Survived", "Dead")
titanic = titanic %>% mutate(family_size = 1 + SibSp + Parch)

titanic %>% 
  group_by(Sex, survived_label, Pclass) %>% 
  summarise(mean = mean(family_size), .groups = "drop") %>% # 显式设置分组规则消除警告
  ggplot(aes(Sex, mean, fill = factor(Pclass), group = factor(Pclass))) + 
  geom_col(position = "dodge") + # 将position参数移至此处
  facet_wrap(~ survived_label)

修改后,每个分面内同性别下不同舱位的柱状图会以并列形式展示,不再堆叠。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 23:15:55