Chapter 12 Default Box Plots in R

Basic box plots:

Example-1:

# Boxplot of MPG by Car Cylinders 
boxplot(mpg~cyl,data=mtcars, main="Car Milage Data", 
   xlab="Number of Cylinders", ylab="Miles Per Gallon",col="lightblue")

Example-2:

par(mfrow=c(2,2), mar=c(3,3,1,0)+.5, mgp=c(1.6,.6,0))
# Box plot of one variable
boxplot(ToothGrowth$len,col="lightblue")
# Box plots by groups (dose)
# remove frame
boxplot(len ~ dose, data = ToothGrowth, frame = FALSE,col="pink")
# Horizontal box plots
boxplot(len ~ dose, data = ToothGrowth, frame = FALSE,
        horizontal = TRUE,col="green")
# Notched box plots
boxplot(len ~ dose, data = ToothGrowth, frame = FALSE,
        notch = TRUE,col="#C861D3")

Change group names:

boxplot(ToothGrowth$len ~ ToothGrowth$dose, data = ToothGrowth, frame = FALSE,
        names = c("Dose 0.5", "Dose 1", "Dose 2"),col="orange")

Change color:

par(mfrow=c(2,2), mar=c(3,3,1,0)+.5, mgp=c(1.6,.6,0))

# Change the color of border using one single color
boxplot(len ~ dose, data = ToothGrowth, frame = FALSE,
        border = "steelblue")
# Change the color of border.
#  Use different colors for each group
boxplot(len ~ dose, data = ToothGrowth, frame = FALSE,
        border = c("#999999", "#E69F00", "#56B4E9"))
# Change fill color : single color
boxplot(len ~ dose, data = ToothGrowth, frame = FALSE,
        col = "steelblue")
# Change fill color: multiple colors
boxplot(len ~ dose, data = ToothGrowth, frame = FALSE,
        col = c("#999999", "#E69F00", "#56B4E9"))

Multiple box plots:

boxplot(len ~ supp*dose, data = ToothGrowth,
        col = c("white", "steelblue"), frame = FALSE)

Main title and axis labels:

# Change axis titles
# Change color (col = "gray") and remove frame
# Create notched box plot
boxplot(len ~ dose, data = ToothGrowth,
        main = "Plot of length by dose",
        xlab = "Dose (mg)", ylab = "Length",
        col = "lightgray", frame = FALSE)

Notched Boxplot:

# Notched Boxplot of Tooth Growth Against 2 Crossed Factors
# boxes colored for ease of interpretation 
boxplot(len~supp*dose, data=ToothGrowth, notch=FALSE, 
  col=(c("orange","darkgreen")),
  main="Tooth Growth", xlab="Suppliment and Dose")

Additional box plots->

  • vioplot function from vioplot package
  • bagplot(x, y) function from aplpack package

Example-1:

# Violin Plots
#install.packages("vioplot")
library(vioplot)
x1 <- mtcars$mpg[mtcars$cyl==4]
x2 <- mtcars$mpg[mtcars$cyl==6]
x3 <- mtcars$mpg[mtcars$cyl==8]
vioplot(x1, x2, x3, names=c("4 cyl", "6 cyl", "8 cyl"), 
   col="lightblue")
title("Violin Plots of Miles Per Gallon")

Example-2:

# Example of a Bagplot
#install.packages("aplpack")
library(aplpack)
## Loading required package: tcltk
attach(mtcars)
bagplot(wt,mpg, xlab="Car Weight", ylab="Miles Per Gallon",
  main="Bagplot Example")