0

I swear I have looked at many questions here to try to find this answer, but have not been able to discover it (including here, here, here, here, and more that I can't go back and find right now).

I think this is a pretty simple question, but it's driving me crazy. I have a dataset

data1  <- structure(list(
Identity = c("Red", "Orange", "Yellow", "Green", "Blue", "Red", "Orange", "Yellow", "Green", "Blue", "Red", "Orange", "Yellow", "Green", "Blue"), 
FavorableLevel = c("Medium", "Medium", "Medium", "Medium", "Medium", "Low", "Low", "Low", "Low", "Low", "High", "High", "High", "High", "High"), 
Value = c(.42, .21, .49, .51, .55, .39, .67, .04, .22, .19, .18, .11, .45, .27, .28)), 
.Names = c("Identity", "FavorableLevel", "Value"), 
row.names = c(NA, -15L), 
class = c("tbl_df", "tbl", "data.frame"))

I am attempting to make a stacked bar graph, but I want the bars ordered by the value of "High" favorability ratings. I can create this graph:

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.

SPTS
  • 13
  • 2

1 Answers1

3

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")

stefan
  • 90,330
  • 6
  • 25
  • 51
  • This worked perfectly. I wish there was an easy way to do it within ggplot so I didn't have to mess with the data structure, but I'll take it! Thank you SO MUCH! – SPTS Jul 15 '22 at 15:22
  • Haha. Of course could you do to the reordering inside the ggplot2 code. But personally I prefer to do such stuff outside of it. – stefan Jul 15 '22 at 15:25