Re: [R] multiple boxplots

From: Marc Schwartz (via MN) <mschwartz_at_mn.rr.com>
Date: Sat 29 Oct 2005 - 04:12:07 EST

On Fri, 2005-10-28 at 10:26 -0700, J.M. Breiwick wrote:
> Hello,
>
> I want to plot 3 boxplots [ par(mfrow=c(3,1)) ] but the first one has 8
> groups, the 2nd has 7 and the third has 6. But I the groups to line up:
>
> 1 2 3 4 5 6 7 8
> 2 3 4 5 6 7 8
> 3 4 5 6 7 8
>
> where the numbers actually refer to years. I suspect I have to manipulate
> the function bxp(). Is there a relatively simple way to do this? Thanks for
> any help.
>
> Jeff Breiwick
> NMFS, Seattle

Here is one approach. It is based upon using 2 principal concepts:

  1. Create the first plot, save the plot region ranges from par("usr") and then use this information for the two subsequent plots, where we use the 'add = TRUE' argument.
  2. Use the 'at' argument to specify the placement of the boxes in the second and third plots to line up with the first.

So:

# Create our data.
dat <- rnorm(80)
years <- rep(1991:1998, each = 10)

# MyDF will be a data frame with two columns and we will use 
# this in the formula method for boxplot.
# The second and third plots will use subset()s of MyDF
MyDF <- cbind(dat, years)

# Set the plot matrix
par(mfrow = c(3, 1))

# Create the first boxplot and save par("usr") boxplot(dat ~ years, MyDF)
usr <- par("usr")

# Now open a new plot, setting it's par("usr") to 
# match the first plot.
# Then use boxplot and set the boxes 'at' x pos 2:8
# and add it to the open plot

plot.new()
par(usr = usr)
boxplot(dat ~ years, subset(MyDF, years %in% 1992:1998),

        at = 2:8, add = TRUE)

# Rinse and repeat ;-)
# Different subset and use 3:8 for 'at'
plot.new()
par(usr = usr)
boxplot(dat ~ years, subset(MyDF, years %in% 1993:1998),

        at = 3:8, add = TRUE)

Replace MyDF in the above with your actual datasets of course.

This would of course be a bit easier if one could set an 'xlim' argument in boxplot(), but this is ignored by bxp().

HTH, Marc Schwartz



R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html Received on Sat Oct 29 04:16:47 2005

This archive was generated by hypermail 2.1.8 : Sat 29 Oct 2005 - 09:41:52 EST