How to change the automatic sorting of X-axis of a bar plot using ggplot2 in R?

If there is a category for which the frequency is significantly different from others then the X-axis labels of the bar plot using ggplot2 are automatically sorted to present the values alternatively. We might want to keep the original sequence of categories that is available in the categorical variable. Therefore, we can store the categorical variable as a factor and then create the bar plot.


Consider the below data frame −

> Group<-c("India","USA","UK","Germany")
> Frequency<-c(12,18,35,20)
> df<-data.frame(Group,Frequency)
> df
Group Frequency
1 India   12
2 USA     18
3 UK      35
4 Germany 20
> library(ggplot2)
> ggplot(df,aes(Group,Frequency))+geom_bar(stat="identity")


Here, we can see that Germany is the last category in Group variable but we might want to create the plot with the same sequence as we have in our variable. This can be done as shown below −

> df$Group<-factor(df$Group, levels = df$Group)
> ggplot(df,aes(Group,Frequency))+geom_bar(stat="identity")