【问题标题】:facet ordering in multilevel ggplot stacked barplot多级ggplot堆叠条形图中的方面排序
【发布时间】:2021-12-08 05:17:24
【问题描述】:

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

一个简单的例子如下:

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)

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

【问题讨论】:

    标签: r ggplot2 bar-chart facet


    【解决方案1】:

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

    您需要在绘图之前手动设置条形部分的最小值和最大值。我在这里使用 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 日创建

    【讨论】:

    • 谢谢,这很有魅力。在我真正的问题中,我还必须在片段中添加标签,这是通过 geom_label(aes(y=ymin+(ymax-ymin)/2)) 完成的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-15
    • 2020-10-06
    • 2020-10-16
    • 1970-01-01
    • 2017-11-07
    • 1970-01-01
    • 2017-07-21
    相关资源
    最近更新 更多