Box plot

Problem

You want to make a box plot.

Solution

This page shows how to make quick, simple box plots with base graphics. For more sophisticated ones, see Plotting distributions (ggplot2)).

Sample data

The examples here will use the ToothGrowth data set, which has two independent variables, and one dependent variable.

  1. head(ToothGrowth)
  2. #> len supp dose
  3. #> 1 4.2 VC 0.5
  4. #> 2 11.5 VC 0.5
  5. #> 3 7.3 VC 0.5
  6. #> 4 5.8 VC 0.5
  7. #> 5 6.4 VC 0.5
  8. #> 6 10.0 VC 0.5

Simple box plots of len against supp and dose:

  1. boxplot(len ~ supp, data=ToothGrowth)
  2. # Even though `dose` is a numeric variable, `boxplot` will convert it to a factor
  3. boxplot(len ~ dose, data=ToothGrowth)

plot of chunk unnamed-chunk-3plot of chunk unnamed-chunk-3

A boxplot of len against supp and dose together.

  1. boxplot(len ~ interaction(dose,supp), data=ToothGrowth)

plot of chunk unnamed-chunk-4

Note that boxplot and plot have much the same output, except that plot puts in axis labels, and doesn’t automatically convert numeric variables to factors, as was done with dose above.

  1. plot(len ~ interaction(dose,supp), data=ToothGrowth)

plot of chunk unnamed-chunk-5