How to Arrange the Bars in ggplot2
How to Arrange the Bars in ggplot2?, The frequencies of several types of data can be shown using bar charts. The bars are arranged in the following sequences by default in ggplot2 bar charts:
Factor levels determine the order of factor variables.
Alphabetical order is used to arrange character variable names.
However, there are times when you could be interested in arranging the bars in a different way. The following data frame is used in this tutorial to demonstrate how to achieve that.
Let’s create data frame
df <- data.frame(team = c('X', 'X', 'X', 'Y', 'Z', 'Z'), points = c(212, 228, 129, 232, 332, 245), rebounds = c(35, 25, 57, 52, 51, 54))
Now we can view the structure of data frame
'data.frame': 6 obs. of 3 variables: $ team : chr "X" "X" "X" "Y" ... $ points : num 212 228 129 232 332 245 $ rebounds: num 35 25 57 52 51 54
Example 1: Order the Bars Based on a Specific Factor Order
The bars will automatically be arranged alphabetically if we try to make a bar chart to show the frequency by team.
library(ggplot2) ggplot(df, aes(x=team)) + geom_bar()
The code below demonstrates how to arrange the bars in a particular order:
Indicate the factor level order.
df$team = factor(df$team, levels = c('Z', 'X', 'Y')) ggplot(df, aes(x=team)) + geom_bar()
Example 2: Order the Bars Based on Numerical Value
The bars can also be arranged according to numerical values. For instance, the code below demonstrates how to use the reorder() function to arrange the bars from highest to lowest frequency:
library(ggplot2) ggplot(df, aes(x=reorder(team, team, function(x)-length(x)))) + geom_bar()
By removing the minus sign from the function() call within the reorder() method, we can also arrange the bars from lowest to highest frequency.
library(ggplot2) ggplot(df, aes(x=reorder(team, team, function(x) length(x)))) + geom_bar()