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

如何使用ggplot2 geom_col结合facet_grid与coord_flip实现左侧分组横条图

解决方案

核心调整逻辑是将原本的列分面改为行分面,同时将分面标签切换到y轴左侧即可实现你要的效果:

library(ggplot2)
library(magrittr)
library(tibble)
set.seed(1234)

countries  <- c('AU', 'NZ', 'UK', 'SA')
retailer   <- c(paste0('rtlr', 1:6))
categories <- c(paste0('cat', 1:4))

df <- tibble(
  countries    = sample(countries,  50, replace = T)
  , categories = sample(categories, 50, replace = T)
  , retailer   = sample(retailer,   50, replace = T)
  , n          = sample(1:200   ,   50, replace = T)
)

df %>%
  ggplot(aes(x = n, y = categories)) +
  geom_col(show.legend = F) +
  facet_grid(
    countries + retailer ~ . # 改为行分面,按国家+零售商垂直排列
    , scales = 'free_y' # 仅y轴自适应,避免x轴刻度不一致
    , switch = 'y' # 分面标签切换到y轴左侧
    , labeller = label_both
  ) +
  # 可选样式优化,让标签更贴合左侧轴
  theme(
    strip.placement = "outside",
    strip.background = element_blank(),
    strip.text.y.left = element_text(angle = 0)
  )

关键修改说明

  • 分面公式从~ countries + retailer改为countries + retailer ~ .,代表按国家、零售商两个维度做垂直方向的行分面,每一行组合对应一个国家+零售商的分组
  • switch参数从x改为y,把分面标签移动到y轴左侧显示
  • 搭配strip.placement = "outside"的主题设置,让分面标签和y轴刻度整合在一起,实现三层分组都在左侧的效果
    该方案基于原生ggplot实现,可直接嵌入shiny应用的renderPlot逻辑中使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 06:15:02