多级ggplot堆叠条形图中的刻面排序

facet ordering in multilevel ggplot stacked barplot

我想以递减的方式对每个条形中的方面进行排序 -> 首先是最高值,然后是下一个,然后是下一个....

一个简单的例子如下:

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)

在示例中,堆栈的顺序不正确。

我对你的例子有点困惑,所以我试着想出一个更直观的例子。

您需要在绘图前手动设置条形部分的最小值和最大值。我在这里用 geom_segment 绘制,但你也可以使用 geom_rect。

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)

reprex package (v2.0.1)

于 2021-10-22 创建