ggplot2 Tip – Reorder

ggplot2 Tip – Reorder

In ggplot2, normally R will graph a bar chart based on alphabetical order. But there are many times that I want the order to be based on the values of the bar chart.

Below is the code used to render the above graph. Currently, is it not great visually to quickly spot the “top” pitchers with home runs against Barry Bonds.

ggplot(data = Barry, aes(x= Pitcher, y = count)) +
   geom_bar(stat = "identity", fill="#FD5A1E") +
   ggtitle("Barry Bonds (Career HRs against)") +
   labs(y = "HRs", x = "Pitcher") +
   theme_minimal() +
   theme(axis.text.x=element_text(face="bold"))

There is a simple attribute you add to the code. The reorder(Column) for ascending order, and reorder(Column, -count) for descending. See below for an example code with the reorder syntax and the output graph.

ggplot(data = Barry, aes(x= reorder(Pitcher, -count), y = count)) +
   geom_bar(stat = "identity", fill="#FD5A1E") +
   ggtitle("Barry Bonds (Career HRs against)") +
   labs(y = "HRs", x = "Pitcher") +
   theme_minimal() +
   theme(axis.text.x=element_text(face="bold"))