UCLA Academic Technology Services HomeServicesClassesContactJobs
Help the Stat Consulting Group by giving a gift             
Loading

Box plots using ggplot2

The examples here are created using R 2.12.2 for Windows XP. The function qplot in package ggplot2 is used for all the examples.

The examples below use hsb2 data set that can be downloaded as follows.

library(ggplot2)
hsb2 <- read.table('http://www.ats.ucla.edu/stat/r/modules/hsb2.csv', header=T, sep=",")
hsb2$female <- factor(hsb2$female, labels = c("male", "female"))
hsb2$ses<- factor(hsb2$ses, labels = c("low", "med", "high"))
qplot(female, write, data = hsb2, geom="boxplot")
 

 

qplot(female, write, data = hsb2, geom="boxplot")+xlab("Gender")
 

 

# adding facet
qplot(female, write, data = hsb2, 
   geom="boxplot")+ xlab("Gender") + facet_grid(ses~., 
   scales="free", space="free") + opts(strip.text.y = theme_text())
 
 

 

# switching to side by side and set the background color to white
qplot(female, write, data = hsb2, 
  geom="boxplot")+ xlab("") + facet_grid(.~ses, scales="free", 
  space="free") + theme_bw() + opts(strip.text.y = theme_text())
 
 
 
# adding raw data points
qplot(female, write, data = hsb2, 
  geom="boxplot")+ geom_point() + xlab("") + facet_grid(.~ses, 
  scales="free",space="free") + theme_bw() + opts(strip.text.y = theme_text())
 

 

# adding jittered raw data points
qplot(female, write, data = hsb2, 
  geom="boxplot")+ geom_jitter() + xlab("") + facet_grid(.~ses, 
  scales="free",space="free") + theme_bw() + opts(strip.text.y = theme_text())

 

# control the amount of jitter
qplot(female, write, data = hsb2, 
  geom="boxplot")+ geom_jitter(position=position_jitter(w=0.1, 
  h=0.1)) + xlab("") + facet_grid(.~ses, scales="free", 
  space="free") + theme_bw()+ opts(strip.text.y = theme_text())

 

# display the value of median for each group
# this requires to get the aggregate data
# we used the function summaryBy in the package called "doBy"
# adding text by adding a layer with gemo = "text"
library(doBy)
a<-summaryBy(write ~ female + ses , hsb2, FUN=c(median)) 

qplot(female, write, data = hsb2, 
  geom="boxplot") + xlab("") +  layer(data = a, mapping = 
  aes(x = female, y= write.median+1, label=round(a$write.median)), 
  geom = "text", color="NavyBlue", size=3.5) +facet_grid(.~ses, 
  scales="free", space="free") + theme_bw()+ opts(strip.text.y = theme_text()) 

 

Last updated on July 15, 2011


How to cite this page

Report an error on this page or leave a comment

UCLA Researchers are invited to our Statistical Consulting Services
We recommend others to our list of Other Resources for Statistical Computing Help
These pages are Copyrighted (c) by UCLA Academic Technology Services


The content of this web site should not be construed as an endorsement of any particular web site, book, or software product by the University of California.