我想設計一個水平 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% 確定這是否是您要執行的操作,但是您可以嘗試使用rows
和cols
參數而不是公式表示法。
例如
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] 删除。
我来说两句