Stacked barchart, independent fill order for each stack

前端 未结 3 680
南方客
南方客 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:39

    The problem is that, in your case, different bars should use the same values (levels) of filling in a different order. This conflicts with the way ggplot works: taking the factor levels (which already have a certain order) and applying them in the same way for each bar.

    A workaround then is... To create many factor levels.

    ggplot(dats, aes(x = id, y = value, fill = interaction(-ordering, id))) + 
      geom_bar(stat = "identity", position = "stack")
    

    This one now is too "generous" by being too detailed. However, what we can do now is to deal with the legend and the different colors:

    dats <- arrange(dats, id, -ordering)
    aux <- with(dats, match(sort(unique(filling)), filling))
    ggplot(dats, aes(x = id, y = value, fill = interaction(-ordering, id))) + 
      geom_bar(stat = "identity", position = "stack") +
      scale_fill_manual("Ordering", values = scales::hue_pal()(4)[dats$filling],
                        labels = with(dats, filling[aux]), 
                        breaks = with(dats, interaction(-ordering, id)[aux]))
    

    Here I first rearrange the rows of dats as to avoid doing that later. Then aux is an auxiliary vector

    aux
    # [1] 3 2 1 8
    

    giving arbitrary positions (one for each) where levels a, b, c, and d (in this order) appear in dats, which again is useful later. Then I simply set corresponding scale values, labels, and breaks... Lastly, I use scales::hue_pal to recover the original color palette.

提交回复
热议问题