Reverse fill order of stacked bars with faceting

前端 未结 1 1857
温柔的废话
温柔的废话 2021-01-16 10:25

I can\'t figure out how to get the fill order to reverse. Basically, I\'m trying to get the guide and the fill to match an intrinsic order of the words from positive to nega

相关标签:
1条回答
  • 2021-01-16 11:00

    To change the order of values in stacked barplot you should use argument order= in aes() of geom_bar() and set name of column necessary for ordering (in this case Response). With function desc() you can set reverse order of bars.

    Using your original data frame (without last line of factor()).

    ggplot(dat, aes(Banner, Proportion/100, fill=Response,
                    label=ifelse(Proportion > 5, percent(Proportion/100), ""))) + 
      geom_bar(position="fill", stat="identity",aes(order=desc(Response))) + 
      geom_text(aes(Banner, Pos/100)) + 
      facet_grid(~Phase) + 
      scale_y_continuous(labels=percent) +
      labs(x="\nCompany", y="\nProportion")
    

    To get correct placement of labels, changed calculation of positions:

    dat <- ddply(dat, .(Banner, Phase), function(x) {
      x$Pos <- (100-cumsum(x$Proportion) + 0.5*x$Proportion)
      x
    })
    

    enter image description here

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