Box plots can be created for individual variables or for variables by group. The syntax is boxplot(x, data=), where x is a formula and data denotes the data frame providing the data. An example of a formula is: y~group, where you create a separate box plot for each value of group.
Use varwidth=TRUE to make box plot widths proportional to the square root of the sample sizes. Use horizontal=TRUE to reverse the axis orientation.
The Standard Box Plot does not indicate outliers. The Modified Box Plot highlights outliers. The Modified Box plot is the default in R.
A <- c(3, 2, 5, 6, 4, 8, 1, 2, 3, 2, 4)
Look at the built-in dataset mtcars.
Now create a box plot for vehicle weight for each type of car.
boxplot(wt~cyl, data=mtcars, main=toupper("Vehicle Weight"), font.main=3, cex.main=1.2, xlab="Number of Cylinders", ylab="Weight", font.lab=3, col="darkgreen")
Let’s create a notched box plot of miles per gallon for each type of car, with different colours for each box. Notched box plots help us to to make a visual comparison across levels and check for equality of medians. If the notches of two boxes do not overlap, this will provide evidence of a statistically significant difference between the medians
boxplot(mpg~cyl, data=mtcars, main= toupper("Fuel Consumption"), font.main=3, cex.main=1.2, col=c("red","blue", "yellow"), xlab="Number of Cylinders", ylab="Miles per Gallon", font.lab=3, notch=TRUE, range = 0)
The notches do not overlap, so we have evidence for a difference in the medians.
NOTE: The range argument determines how far the plot whiskers extend out from the box. If range is positive, the whiskers extend to the datum that is no more than range times the interquartile range from the box. The argument range = 0 ensures that the whiskers extend to the data extremes. The argument horizontal=TRUE creates horizontal bars.
That wasn’t so hard! In Part 14 we will look at further plotting techniques in R.
About the Author: David Lillis has taught R to many researchers and statisticians. His company, Sigma Statistics and Research Limited, provides both on-line instruction and face-to-face workshops on R, and coding services in R. David holds a doctorate in applied statistics.