简体   繁体   中英

How to Use ggplot2 geom_col with facet_grid and coord_flip

I would like to design a horizontal ggplot barchart with 3 groups on the left axis (country, retailer and category). Following inspiration from R ggplot // Multiple Grouping in X-axis I can design it on the x axis, however, when I then apply coord_flip the country and retailer groups remain on the x axis. How can the also be placed to the left please?

I have attempted with both coord_flip (Attempt 1) and swapping x and y in the initial call to ggplot (Attempt 2) without success. Ultimately this doesn't require to be in a ggplot, but I do require to house it in a shiny app.

Thanks in advance.

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
    )

not 100% sure if this is what you're looking to do, but you can try using the rows and cols arguments instead of the formula notation.

For example

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()

(I don't have access to my computer and running R online, thus struggling to embed the resulting figure, apologies)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM