Home > Enterprise >  facet ordering in multilevel ggplot stacked barplot
facet ordering in multilevel ggplot stacked barplot

Time:10-23

I would like to order the facets within each bar in a decreasing manner -> highest value first, then next, then next....

A simple example would be the following:

library(ggplot) 
library(forcats)

mpgtest <- mpg 

mpgtest$class <- fct_reorder2(mpgtest$class, mpgtest$manufacturer, mpgtest$cyl)

ggplot(mpgtest, aes(x=manufacturer, y = cyl, fill = class))  
geom_col()  
facet_wrap(.~year)

In the example, the stacks are not ordered correctly.

CodePudding user response:

I got a little confused working with your example so I tried to come up with a more intuitive example.

You need to set the min and max for the bar sections manually before plotting. I plotted here with geom_segment, but you could probably use geom_rect as well.

library(tidyverse)

inventory <- 
tibble::tribble(
  ~month,    ~store,     ~item, ~stock_count,
   "May", "store A", "bananas",          30L,
   "May", "store A", "oranges",          10L,
   "May", "store A", "mangoes",          10L,
   "May", "store A",   "kiwis",           4L,
   "May", "store B", "bananas",          15L,
   "May", "store B", "oranges",           5L,
   "May", "store B", "mangoes",           50L,
   "May", "store B",   "kiwis",           2L,
  "June", "store A", "bananas",          30L,
  "June", "store A", "oranges",          10L,
  "June", "store A", "mangoes",          10L,
  "June", "store A",   "kiwis",           4L,
  "June", "store B", "bananas",          15L,
  "June", "store B", "oranges",           5L,
  "June", "store B", "mangoes",           50L,
  "June", "store B",   "kiwis",           2L
  )

fruit_colors <- c("bananas" = "yellow2", 
            "oranges" = "orange2", 
            "mangoes" = "indianred3", 
            "kiwis" = "yellowgreen")

inventory %>% 
  group_by(month, store) %>% 
  arrange(-stock_count, .by_group = T) %>% 
  mutate(ymax = cumsum(stock_count), 
         ymin = lag(ymax, default = 0)) %>% 
  ungroup() %>% 
  ggplot()   
  geom_segment(aes(y = ymin, 
                yend = ymax,
                x = store, 
                xend = store,
                color = item), 
            size = 10)   
  scale_color_manual(values = fruit_colors)   
  facet_wrap(~month)

Created on 2021-10-22 by the reprex package (v2.0.1)

  • Related