library(ggplot2)
Sometimes when creating a bar plot with categorical labels, you will find that ggplot will order the bars in alphabetical order.
df <- data.frame(f.name = c("Bob", "Tom", "Jane", "Robert", "Jen"), age = c(23, 34, 32, 29, 23))
p <- ggplot(df, aes(x = f.name, y = age))
p <- p + geom_bar(stat="identity", color='skyblue',fill='steelblue')
p <- p + theme(axis.text.x=element_text(angle=45, hjust=1))
p
A simple way, to reorder them in ascending or descending order is to use the reorder
command.
Here is an example where we use a minus sign on the age
variable indicating we want to display the bars in descending order.
p <- ggplot(df, aes(x = reorder(f.name, -age), y = age))
p <- p + geom_bar(stat="identity", color='skyblue',fill='steelblue')
p <- p + theme(axis.text.x=element_text(angle=45, hjust=1))
p