
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
Change Order of Boxplot Using ggplot2 in R
To change the order of boxplot by means using ggplot2, we can use reorder function inside aes of ggplot. For example, if we have a data frame called df that contains two columns say x (categorical) and y(count) then the boxplot ordered by means can be created by using the command ggplot(df,aes(x=reorder(x,y,mean),y))+geom_boxplot()
Example
Consider the below data frame −
> x<-c(rep(c("A","B","C"),times=c(10,5,5))) > y<-c(rpois(10,25),rpois(5,10),rpois(5,2)) > df<-data.frame(x,y) > df
Output
x y 1 A 22 2 A 17 3 A 20 4 A 36 5 A 34 6 A 25 7 A 25 8 A 30 9 A 23 10 A 29 11 B 8 12 B 8 13 B 6 14 B 8 15 B 12 16 C 0 17 C 4 18 C 3 19 C 2 20 C 1
Loading ggplot2 package and creating boxplot for categories in x −
> library(ggplot2) > ggplot(df,aes(x,y))+geom_boxplot()
Output
Creating boxplot for categories in x ordered by mean of y −
> ggplot(df,aes(x=reorder(x,y,mean),y))+geom_boxplot()
Output
Advertisements