如何將 ggplot2 geom_col 與 facet_grid 和 coord_flip 一起使用

卡勒姆

我想設計一個水平 ggplot 條形圖,左軸上有 3 個組(國家、零售商和類別)。遵循R ggplot // X 軸多重分組的靈感,我可以在 x 軸上設計它,但是,當我應用 coord_flip 時,國家和零售商組仍保留在 x 軸上。請問怎麼也可以放在左邊?

我曾嘗試使用 coord_flip(嘗試 1)並在對 ggplot(嘗試 2)的初始調用中交換 x 和 y,但沒有成功。最終這不需要在 ggplot 中,但我確實需要將它放在一個閃亮的應用程序中。

提前致謝。

library(ggplot2)
library(magrittr)
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)
)

# Attempt 1

df %>%
  ggplot(aes(x = categories, y = n)) +
  geom_col(show.legend = F) +
  facet_grid(
    ~ countries + retailer
    , scales = 'free'
    , switch = 'x'
    , labeller = label_both
    ) +
  coord_flip()

 # Attempt 2
df %>%
  ggplot(aes(x = n, y = categories)) +
  geom_col(show.legend = F) +
  facet_grid(
    ~ countries + retailer
    , scales = 'free'
    , switch = 'x'
    , labeller = label_both
    )
傑博

不能 100% 確定這是否是您要執行的操作,但是您可以嘗試使用rowscols參數而不是公式表示法。

例如

df %>%
  ggplot(aes(x = categories, y = n)) +
  geom_col(show.legend = F) +
  facet_grid(
    rows = vars(countries, retailer) 
    , scales = 'free'
    , switch = 'x'
    , labeller = label_both
    ) +
  coord_flip()

(我無法訪問我的計算機並在線運行 R,因此難以嵌入結果圖,抱歉)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

ggplot2:具有coord_flip()和自由刻度的geom_pointrange()facet_grid()

如何在ggplot2中一起使用coord_carteisan和coord_flip

在ggplot2中,coord_flip和自由缩放不一起使用

ggplot2 facet_grid:如何修复geom_col中列之间的不同间距

Ggplot2:coord_polar() 和 geom_col()

使用gganimate和view_follow和geom_tile时,如何摆脱由coord_flip引起的轴闪烁?

ggplot2 coord_flip()与geom_text

ggplot2:将geom_dotplot与facet_grid一起使用时,没有自由轴缩放

将geom_boxplot与facet_grid和free_y一起使用

R Shiny和ggplot2:如何使geom_col的边框透明?

使用facet_grid和多个数据点(R ggplot2)时,将geom_point和geom_line组合

如何在ggplot2 :: facet_grid中格式化网格标题和条目

将coord_flip与geom_boxplot一起使用时,删除重复的轴标签

ggplot2:如何使geom_text()与facet_grid()很好地玩?

水平ggplot2 :: geom_violin不带coord_flip

ggplot2:如何获取facet_grid()的labeller = label_both和facet_wrap()的ncol选项的合并功能?

如何使用ggplot2 facet_grid注释没有数据的构面?

如何在ggplot2中使用facet_grid制作甜甜圈图?

如何使用facet_grid(ggplot2)在每个构面上绘制多条线

如何在ggplot2的甘特图R中使用facet_grid

将ggplot2和facet_grid一起用于连续变量和分类变量(R)

R / ggplot 2-使用Facet_grid和geom直方图/误差线处理不均匀的组大小

如何固定纵横比并在ggplot2中应用coord_flip?

ggplot2标签不会与geom_col条一起闪避

ggplot2:geom_violin(),geom_text()与facet_grid()一起打印每个因素中不包括NA的总行数

在 ggplot2 中使用 coord_flip() 后更改条形图中条形的顺序

结合 facet_grid (ggplot2) 和 denscomp (fitdistrplus)

使用ggplot和facet_grid指定错误栏

如何使用 ggplot2 中的 position_dodge() 为 geom_col() 中的每个条获得相同的宽度?