- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
Example
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")
Output
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")
Output
- Related Articles
- How to change the Y-axis values in a bar plot using ggplot2 in R?
- How to convert the X-axis label in a bar plot to italic using ggplot2 in R?
- How to change the color of bars of a bar plot using ggplot2 in R?
- How to change the color of X-axis label using ggplot2 in R?
- How to X-axis labels to the top of the plot using ggplot2 in R?
- How to create a bar plot using ggplot2 with percentage on Y-axis in R?
- How to change legend values in a bar plot created by using ggplot2 in R?
- How to reverse the bars of a bar plot a using ggplot2 in R?
- How to change the thickness of the borders of bars in bar plot created by using ggplot2 in R?
- How to change the border style of a plot using ggplot2 in R?
- How to change the position of X-axis in base R plot?
- How to change the orientation and font size of x-axis labels using ggplot2 in R?
- How to create transparent bar plot using ggplot2 in R?
- How to increase the space between bars of a bar plot using ggplot2 in R?
- How to create a bar plot with ggplot2 using stat_summary in R?

Advertisements