This is different to existing questions. Other answers pointed to refer to moving entire bars according to a specified order. I would like to sort the resulting bars according to one element within the stacked bars.
I've created a stacked bar plot in R. This is the data set:
dput(Pitch_third)
structure(list(Team = c("Millwall", "Birmingham", "Sheffield United",
"Rotherham", "Middlesbrough", "Wigan", "Aston Villa", "Blackburn",
"Bolton", "Brentford", "Bristol City", "Leeds", "Preston", "Queens Park Rangers",
"Stoke", "Derby", "Ipswich", "Norwich", "West Bromwich Albion",
"Nottingham Forest", "Swansea", "Hull", "Reading", "Sheffield Wednesday"),
Own_3rd = c(0.25, 0.25, 0.25, 0.29, 0.27, 0.28, 0.28, 0.3,
0.29, 0.28, 0.28, 0.3, 0.28, 0.3, 0.27, 0.28, 0.3, 0.29, 0.29,
0.3, 0.31, 0.3, 0.3, 0.31),
Middle_3rd = c(0.41, 0.42, 0.43,
0.4, 0.43, 0.42, 0.44, 0.41, 0.42, 0.42, 0.43, 0.42, 0.42, 0.42,
0.45, 0.45, 0.43, 0.44, 0.44, 0.43, 0.44, 0.45, 0.45, 0.45),
Final_3rd = c(0.35, 0.33, 0.32, 0.31, 0.3, 0.3, 0.29, 0.29,
0.29, 0.29, 0.29, 0.29, 0.29, 0.29, 0.28, 0.27, 0.27, 0.27,
0.27, 0.26, 0.26, 0.25, 0.25, 0.25)),
row.names = c(NA, -24L),
class = "data.frame")
Then I've created a tibble called Pitch_third
from this data.
Then plotted it with this:
Pitch_third %>%
gather(variable, value, Own_3rd:Final_3rd) %>%
ggplot(aes(x = Team, y = value, fill = variable)) +
geom_bar(position = "fill", stat = "identity") +
coord_flip()
This is the resulting plot:
How can I sort the plot so that teams are sorted by the variable Final_3rd rather than alphabetically?
I have tried to use arrange()
to sort the tibble by Final_3rd
but I think gather()
might be messing with that after.
Pitch_third <- arrange(Pitch_third, desc(Final_3rd))