Home > Enterprise >  Reorder Bars of a Stacked Barchart in R
Reorder Bars of a Stacked Barchart in R

Time:07-16

I swear I have looked at many questions here to try to find this answer, but have not been able to discover it (including enter image description here

Using this code (Obviously labels and such need cleaned up):

ggplot(data1, 
   aes(fill=factor(FavorableLevel, levels = c("Low","Medium","High")), 
       y=Value, 
       x=Identity))   
geom_bar(position="fill", stat="identity")

But how can I reorder the bars so that they are sorted in ascending order by the value of "High"? I've tried fct_reorder in a couple of different ways, but I could be using it wrong. I've also tried answers on the various other places linked above, but it's not come to me yet.

CodePudding user response:

One option would be to reorder your Identity column by a helper Value "column" where you set the values for non-High categories to zero and use FUN=sum:

data1$Identity <- reorder(data1$Identity, ifelse(!data1$FavorableLevel %in% "High", 0, data1$Value), FUN = sum)

library(ggplot2)

ggplot(
  data1,
  aes(
    fill = factor(FavorableLevel, levels = c("Low", "Medium", "High")),
    y = Value,
    x = Identity,
  )
)  
  geom_bar(position = "fill", stat = "identity")

  • Related