Stacked barchart, independent fill order for each stack

前端 未结 3 684
南方客
南方客 2020-11-28 15:58

I\'m facing a behaviour of ggplot2, ordering and stacked barplot that I cannot understand.
I\'ve read some question about it (here,here and so on), but unlu

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-28 16:31

    If you use separate geom_bars, you can make the orders different.

    dats %>% 
      ggplot(aes(x = id, y = value, fill = reorder(filling,-ordering))) + 
        geom_bar(stat = "identity", position = "stack", data = dats %>% filter(id == 1)) +
        geom_bar(stat = "identity", position = "stack", data = dats %>% filter(id == 2)) +
        geom_bar(stat = "identity", position = "stack", data = dats %>% filter(id == 3)) +
        guides(fill=guide_legend("ordering")) 
    

    More generally:

    bars <- map(unique(dats$id)
                , ~geom_bar(stat = "identity", position = "stack"
                           , data = dats %>% filter(id == .x)))
    
    dats %>% 
      ggplot(aes(x = id, y = value, fill = reorder(filling,-ordering))) + 
        bars +
        guides(fill=guide_legend("ordering"))
    

提交回复
热议问题