The context
The following data set contains information on how many bad
, alright
and good
students there are in the departments of a school.
students <- data_frame(
department = factor(c("Maths", "Physics", "Economics")),
bad = c(15, 20, 8),
alright = c(10, 22, 17),
good = c(8, 12, 5)
)
I tidy the data set and then use it to make a stacked bar chart to visualize the numbers of students in each category and in each department:
tidy_students <- students %>%
gather(key = "student_quality", value = "number", -department)
ggplot(data = tidy_students, aes(x = department, y = number, fill = student_quality)) +
geom_bar(stat = "identity") +
coord_flip()
My goal
I would like to be able to reorder the bars according to the sub-categories of students. For example, if I want to reorder the bars in descending order based on the number of alright students, then the bar on top would be for the Physics department, followed by the Economics bar and finally the Maths bar.
The actual data I am working with has many more categories (departments) and sub-categories (student quality) and I would like to be able to reorder the bar according to any sub-category.
How can I achieve this? Your help is much appreciated.