Skip to content
Prev 68076 / 398502 Next

controlling the x axis of boxplots

Hi Chris,

You can get the desired effect by using the "at" argument to boxplot,
and by setting up the plot dimensions manually.

men <- data.frame(grp=rep(letters[c(1, 2, 4, 6)], each=10),
                  response=rnorm(40))
women <- data.frame(grp=rep(letters[c(2:5, 7)], each=10),
                    response=rnorm(50))

## Determine all levels used, the number of levels, and appropriate
## xlim for the plot
grp.levs <- sort(unique(c(levels(men$grp), levels(women$grp))))
nlevs <- length(grp.levs)
xlim <- c(.5, nlevs+.5)

## Determine which of the levels are present in men and women; these
## are the x coordinates to draw the boxes (this will need tweaking if
## you are using ordered factors).
at.men <- match(levels(men$grp), grp.levs)
at.women <- match(levels(women$grp), grp.levs)

par(mfrow=c(2,1))
## boxplot() does not take an xlim argument, so you'll have to set up
## the plot yourself (including the axis, since the default is not
## appropriate for a boxplot).
plot(NA, type="n", xlim=xlim, ylim=range(men$response), xlab="",
     ylab="Response", xaxt="n")
axis(1, 1:nlevs, grp.levs)
boxplot(response ~ grp, men, at=at.men, add=TRUE)

plot(NA, type="n", xlim=xlim, ylim=range(women$response),
     xlab="Group", ylab="Response", xaxt="n")
axis(1, 1:nlevs, grp.levs)
boxplot(response ~ grp, women, at=at.women, add=TRUE)

Cheers,
Rich
On 4/20/05, Chris Evans <chris at psyctc.org> wrote: