mjhendrickson/Learning-R

Reorder geom_bar based on count

mjhendrickson opened this issue · 2 comments

Determine best way to reorder output of geom_bar to plot descending based on count.

Need a way to do this that isn't manual. reorder appears to be a good possibility, but cannot get it to work.

# Course code
# Original
ggplot(data = HxMx) +
  geom_bar(mapping = aes(x = course_code, fill = institution), stat = "count") +
  scale_fill_manual(values = c("#C90016","#8A8B8C")) + # hex colors matching institution
  scale_y_continuous(name = " ", labels = comma) +
  theme(axis.title.x = element_blank(),
        axis.text.x = element_text(angle=90, vjust=0.5)) +
  labs(title = "Course Code")
# Sort Option 1
ggplot(data = HxMx) +
  geom_bar(mapping = aes(x = course_code, fill = institution), stat = "count") +
  scale_fill_manual(values = c("#C90016","#8A8B8C")) + # hex colors matching institution
  scale_x_discrete(name = " ", limits = c("CS50x","6.00x","6.002x","ER22x","PH207x",
              "PH278x","8.02x","CB22x","14.73x","7.00x","3.091x","8.MReV","2.01x")) +
  scale_y_continuous(name = " ", labels = comma) +
  theme(axis.title.x = element_blank(),
        axis.text.x = element_text(angle=90, vjust=0.5)) +
  labs(title = "Course Code")
# Sort Option 2
ggplot(data = HxMx) +
  geom_bar(mapping = aes(x = course_code, fill = institution), stat = "count") +
  scale_fill_manual(values = c("#C90016","#8A8B8C")) + # hex colors matching institution
  scale_x_discrete(name = " ", limits = c("CS50x","ER22x","PH207x","PH278x","CB22x",
                  "6.00x","6.002x","8.02x","14.73x","7.00x","3.091x","8.MReV","2.01x")) +
  scale_y_continuous(name = " ", labels = comma) +
  theme(axis.title.x = element_blank(),
        axis.text.x = element_text(angle=90, vjust=0.5)) +
  labs(title = "Course Code")

output 1
output 2
output 3

For option 1, you can use forcats::fct_infreq():

geom_bar(aes(x = forcats::fct_infreq(course_code), fill = prescription))

It worked! Many thanks @markroepke!
ggplot(data = HxMx) + geom_bar(mapping = aes(x = fct_infreq(course_code), fill = institution)) + #removed forcats:: since package was pre-loaded scale_fill_manual(values = c("#C90016","#8A8B8C")) + # hex colors matching institution scale_y_continuous(name = " ", labels = comma) + theme(axis.title.x = element_blank(), axis.text.x = element_text(angle=90, vjust=0.5)) + labs(title = "Course Code")

Looks like forcats::fct_reorder should work for option 2, but I haven't quite gotten that to work.

At the very least, it works for what I need. Thanks again!