How to change the order of bars in bar chart in R ?
In this article, we will discuss how to change the order of bars in bar chart in R programming language. We can change the order of bars by using two plots ggplot and barplot.
Method 1: Ggplot re-ordering
Firstly create a sample dataset and plot the graph-Manual. Now let’s reorder them accordingly.
Dataset in Use:
Reordering in ggplot is done using theme() function. Within this, we use axis.text.x with the appropriate value to re-order accordingly. By default, geom_bar uses stat=”bin”. This makes the height of each bar equal to the number of cases in each group, If you want the heights of the bars to represent values in the data, use stat=”identity” and map a value to the y aesthetic.
- geom_bar() : Use for the Bar charts
geom_bar( mapping = NULL, data = NULL, stat = “count”, color=’blue’; fill=’yellow’ width = NULL, na.rm = FALSE, orientation = NA, show.legend = NA,…,)
- Theme: Themes can be used to give plots a consistent customized look.
theme( line, rect, text, title, aspect.ratio, axis.text.x, axis.text.x.top, axis.text.x.bottom,)
- line : all line elements (element_line())
- rect :all rectangular elements (element_rect())
- text : all text elements (element_text())
- title :all title elements: plot, axes, legends (element_text(); inherits from text)
- aspect.ratio :aspect ratio of the panel.
- axis.text.x : labels along with axes (element_text()). Specify all axis labels (axis.text), labels
To reorder bars manually, you have to pass stat=”identity” in the geom_bar() function.
Re-ordering the in ascending and descending order
The reorder function is used here to change the order of the graphs.
ggplot(dataframe name, aes(x=reorder(column1,±column2),y=column2)
Here if you want ascending order then you’ll use ‘+’ plus sign, if you want in descending order then you should use ‘-‘ minus sign.
Note: Column2 must be the column with numeric data.
Example: Let us first show the same bar plot in ascending order.
Example: Now let’s look at descending ordered plot
Method 2: Using Barplot re-ordering
Firstly create a sample dataset and plot the graph. Now let us look at the reordering of the bars.
Dataframe in use:
In R, barplot() function
barplot(height, name.args = NULL, col = NULL, main = NULL)
- height: You can specify either a Vector or a Matrix of values.
- name.args :a Vector of names you want to plot below each bar or group of bars in an R bar chart.
For manual ordering pass the order to the x-axis while creating the dataframe.
Re-ordering the graph in ascending and descending order
The function used here is the order (order returns a permutation that rearranges its first argument into ascending or descending order)
order(…, na.last = TRUE, decreasing = FALSE)
na.last: for controlling the treatment of NAs
Let us first look at the ascending ordered plot.
Now let us look at the descending ordered plot.