Box Plots of Two-Way Layout

This example demonstrates how to draw box plots for a two-way analysis of variance. This code, originally by Roger Bivand, is taken from example(boxplot). See the R Graph Gallery for a slightly different version of this plot.

##  Load the data.

require( package = "datasets" )

##  Use the default device.

get( getOption( "device" ) )()

##  Draw the first set of box plots, for supp == "VC".
##  The at argument shifts the box plots to the left by 0.2 units
##  so they won't overlap the box plots for supp == "OJ".
##  The yaxs argument labels the y axis using the original data range.
##  The boxwex argument scales the widths of the boxes, making them narrow
##  so they won't overlap.

boxplot(
    formula = len ~ dose,
    data    = ToothGrowth,
    boxwex  = 0.25,
    at      = 1:3 - 0.2,
    subset  = supp == "VC",
    col     = "yellow",
    main    = "Guinea Pigs' Tooth Growth",
    xlab    = "Vitamin C dose mg",
    ylab    = "tooth length",
    ylim    = c( 0, ceiling( max( ToothGrowth$len ) ) + 1 ),
    yaxs    = "i" )

##  Add the second set of box plots, for supp == "OJ".
##  The at argument shifts the box plots to the right by 0.2 units
##  so they won't overlap the box plots for supp == "VC".

boxplot(
    formula = len ~ dose,
    data    = ToothGrowth,
    boxwex  = 0.25,
    at      = 1:3 + 0.2,
    subset  = supp == "OJ",
    col     = "orange",
    add     = TRUE )

##  Add a legend.

legend(
    x      = 2,
    y      = 9,
    legend = c( "Ascorbic acid", "Orange juice" ),
    fill   = c( "yellow", "orange" ) )

The output is:

Box plots of ToothGrowth data

Box plots of ToothGrowth data