Set the order of a stacked bar chart by the value of one of the variables

后端 未结 2 1775
情歌与酒
情歌与酒 2020-12-12 00:39

I\'ve been asked to produce a stacked bar chart with bars and values that are stacked and ordered in a precise manner.

In this case \"A3\" on the left, \"A2\" in th

相关标签:
2条回答
  • 2020-12-12 01:05

    You already have plotOrder, but you need to apply it to reorder x rather than fill...

    stackedBarPlot <- 
      ggplot(data) +
      aes(x = reorder(ValueName,-plotOrder), 
          y = Percent, 
          fill = Response) +
      geom_bar(position = "fill", stat = "identity") +
      coord_flip()
    

    0 讨论(0)
  • 2020-12-12 01:25

    With a little pre-calculation of the order, this is not so hard:

    library(magrittr)
    library(dplyr)
    
    o <- d %>% filter(Response == "A1") %>% arrange(Percent) %>% extract2("ValueName")
    
    d %>% 
      mutate(ValueName = factor(ValueName, o)) %>% 
      ggplot() +
      aes(x = ValueName, y = Percent, fill = reorder(Response, plotOrder)) +
      geom_bar(position = "fill", stat = "identity") +
      coord_flip()
    

    0 讨论(0)
提交回复
热议问题