- 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 create a bar chart using ggplot2 with facets that are in the order of the data in R?
Since visualization is an essential part of data analysis, we should make sure that the plots are created in a form that is easily readable for users. For this purpose, the facets in a bar chart helps us to understand the factor variable levels for another factor. To create such type of bar chart, we can use facet_grid function of ggplot2 package.
Example
Consider the below data frame −
> set.seed(99) > y<-sample(1:100,50,replace=TRUE) > class<-rep(c(letters[1:5]),times=10) > quantity<-as.factor(rep(c(5,10,15,20,25),each=10)) > df<-data.frame(y,class,quantity)
Here, we have class and quantity as factor variables. Suppose we want to use quantity as a facet.
Loading ggplot2 package −
> library(ggplot2)
Creating the plot with class on X-axis and y on Y-axis without any facet −
> ggplot(df,aes(class,y))+ + geom_bar(stat="identity")
Output
Creating the plot with class on X-axis, y on Y-axis, and quantity as facet −
> ggplot(df,aes(class,y))+ + geom_bar(stat="identity")+ + facet_grid(.~quantity)
Output
- Related Articles
- How to create facets in vertical order using ggplot2 in R?
- How to create bar chart using ggplot2 with chart sub-title in R?
- How to create the bar chart with ggplot2 using color brewer in R?
- How to create a bar chart for single vector using ggplot2 in R?
- How to create a horizontal bar chart using ggplot2 with labels at inside end of the bars in R?
- How to create facetted plot with facets in horizontal direction using ggplot2 in R?
- How to create a line chart using ggplot2 that touches the edge in R?
- Create stacked bar chart with percentages on Y-axis using ggplot2 in R.
- How to create a bar chart using ggplot2 with dots drawn at the center of top edge of the bars in R?
- How to create a bar plot with ggplot2 using stat_summary in R?
- How to create a bar chart using plotly in R?
- How to create a point chart with empty points using ggplot2 in R?
- How to create a line chart using ggplot2 with larger width in R?
- How to create a line chart using ggplot2 with a vertical line in R?
- How to create a line chart for a subset of a data frame using ggplot2 in R?

Advertisements