
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Create Bar Chart Using ggplot2 with Ordered Facets 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
Advertisements