How to reorder variables in ggplot based on the percentage selecting a particular value

29 views Asked by At

I'm trying to reorder a graph so that the variables are descending based on how many people selected the "Use and did learn" option, but I cannot quite figure out how to do it. That is, I want the variable with the greatest percentage of those selecting "Use and did learn" at the top and the variables with the fewest selections of "Use and did learn" at the bottom. For reference, Variable is simply variable name and TransformedValue is a dummy value I gave to each value (the answer options). "Use and did learn" has a TransformedValue of 2. This is what I have so far: Attempted plot here

g2 <-ggplot() +
  geom_bar(data = Q3Summary, 
           aes(x = reorder(Variable, TransformedValue, FUN=mean, decreasing=TRUE),
               y = Percentage, fill = as.factor(TransformedValue)),
           position = "stack", stat = "identity") +
  coord_flip() +
  ggtitle("How did Today's event affect your decision-making?") +
  ylab("Percentage") +
  xlab("Practice") +
  scale_fill_manual(values = wes_palette("IsleofDogs2", 5), drop = FALSE,
                    breaks = names(custom_labels), labels = custom_labels, name = "Practice Used?") +
  theme(legend.position = "bottom")

g2

I tried the reorder function, and used it based on mean and descending, but because I'm interested in ordering based on a value elected and not on an actual variable, I can't figure out how to make the code work. I expected my variables to then be in the ordered by which one had the highest percentage of those selecting "Use and did learn" but it just reorganized the order.

0

There are 0 answers