代码之家  ›  专栏  ›  技术社区  ›  Joe

创建堆叠条形图

  •  1
  • Joe  · 技术社区  · 2 年前

    我正试图使用ggplot创建一个堆叠条形图,但无法将多个堆叠添加到我的条形图中。我试图让每个堆栈显示主、次和后16的细分(用不同的颜色表示),而总高度表示总高度。正如你所看到的,下面的条形图并不完全正确,因为我缺少表示细分的coours,我很确定这将来自geom_col()参数,但不确定修复方法。

    data:
    df <- read_table("region    total    primary   secondary    post16
                East      21       4         8            9
                Mid       28       3         15           10
                North     7        2         4            1
                South     13       3         5            5")
    
    
    code:
     ggplot(df, aes(x = as.factor(region), y = total, fill = "total")) +
      geom_col() +
      geom_col(aes(y = primary, fill = "prim")) +
      geom_col(aes(y = secondary, fill = "seco")) +
      geom_col(aes(y = post16, fill = "p16")) +
      coord_flip()
    

    当前绘图

    enter image description here

    1 回复  |  直到 2 年前
        1
  •  2
  •   M.Viking    2 年前

    这里有点重写。关键是转换数据 into long form :

    library(tidyverse)
    
    df <- read_table("region    total    primary   secondary    post16
                    East      21       4         8            9
                    Mid       28       3         15           10
                    North     7        2         4            1
                    South     13       3         5            5")
    
    df %>% 
      dplyr::select(-total) %>% 
      pivot_longer(-region) %>% 
      mutate(name = fct_relevel(name, "primary", "secondary", "post16")) %>% 
      ggplot(aes(x = region, y = value, fill = name)) + 
        geom_col() + 
        coord_flip()
    

    enter image description here