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

按*one*组的升序重新排列分组条形图

  •  1
  • Loz  · 技术社区  · 6 月前

    我有一个df:

    df1 <- data.frame(ID = c('a', 'b', 'c', 'c1', 'd', 'e', 'f', 'g', 'h', 'h1', 
                             'a', 'b', 'c', 'c1', 'd', 'e', 'f', 'g', 'h', 'h1'),
                      val = c(22, 15, 14, 17, 13, 16, 15, 12, 11, 12, 12, 16,
                              16, 16, 14, 17, 16.5, 13, 12, 12),
                      time = c("time1", "time1", "time1", "time1", "time1", "time1",
                               "time1", "time1", "time1", "time1","time2", "time2",
                               "time2", "time2", "time2", "time2", "time2", "time2", 
                               "time2", "time2"))
    

    我想按升序重新排列条形图 val 但当时间==时间1时,而目前我认为以下是基于时间1+时间2的累积val对条形图进行排序的:

    ggplot(df1, aes(x=reorder(ID, val), y=val, fill=time)) +
      geom_bar(stat="identity", width=0.5, position=position_dodge()) 
    
    1 回复  |  直到 6 月前
        1
  •  1
  •   Axeman    6 月前

    有时对数据进行排序很方便。帧本身,然后使用 fct_inorder 要直接使用该订单:

    library(forcats)
    library(dplyr)
    
    arrange(df1, time, val) |> 
      ggplot(aes(fct_inorder(ID), y=val, fill=time)) +
      geom_col(width=0.5, position=position_dodge()) 
    

    或者,使用 fct_reorder2 :

    ggplot(df1, aes(fct_reorder2(ID, desc(time), desc(val)), y=val, fill=time)) +
      geom_col(width=0.5, position=position_dodge())
    

    enter image description here