library(dplyr)library(ggplot2)
%>% mtcars # data wrangling mutate(cars = rownames(mtcars)) %>% arrange(mpg) %>% mutate( mpg.z.score = (mpg - mean(mpg)) / sd(mpg), cars = factor(cars, levels = cars), # put the new variable at the 2nd column .after = 1) %>% # visualization ggplot(aes(x = cars, y = mpg.z.score, fill = factor(gear))) + geom_col() + geom_hline(yintercept = 0) + theme_minimal() + labs(fill = "Gear", y = "miles per gallon (standardized)", x = NULL) + theme(legend.position = c(.2, .8), axis.text.x = element_text(angle = 60, hjust = 1))
Use Ordered Barplot with ggplot2 to Visualize Cars’ Engine Efficiency

In this visualization, we create a bar chart to compare cars’ mileage per gallon (mpg) using the R built-in dataset mtcars
. Technically, we first normalize the mpg values into z-score, and then arrange the dataset based on the normalized result. You can find a complete guide here how to reorder graphic elements in ggplot2.
Continue Exploring — 🚀 one level up!
In the charts above, the car labels are positioned far away from the bars. This can hurt the plot readability, and much white space is not effectively utilized. Instead, check this improved visualization to learn how to position the labels directly on the side of the bars.
Reordering of graphical elements is one of the most used and powerful techniques in data visualization, as illustrated in the above two examples. In the following stacked area / alluvial plot, ribbons are stacked in well-designed order such that color gradients can be leveraged to distinguish different countries and continents.