[R] bwplot: using a numeric variable to position boxplots

Michael Friendly friendly at yorku.ca
Thu May 3 16:32:50 CEST 2012


[Env: R 2.14.2 / Win Xp]

In the examples below, I'm using lattice::bwplot to plot boxplots of 4 
variables, grouped by a factor 'epoch'
which also corresponds to a numeric year.  I'd like to modify the plots 
to position the boxplots according to
the numeric value of year, but I can't figure out how to do this.

Also, I'd to modify the strip labels that give the variable names to use 
longer variable labels I define below as
vlab.

 > install.packages("heplots", repos="http://R-Forge.R-project.org")
 > # requires heplots 0.9-12 for Skulls data
 > library(heplots)
 > data(Skulls)
 >
 > # make shorter labels for epochs
 > Skulls$epoch <- factor(Skulls$epoch, 
labels=sub("c","",levels(Skulls$epoch)))
 > # create year variable
 > Skulls$year <- rep(c(-4000, -3300, -1850, -200, 150), each=30)
 > str(Skulls)
'data.frame':   150 obs. of  6 variables:
  $ epoch: Ord.factor w/ 5 levels "4000BC"<"3300BC"<..: 1 1 1 1 1 1 1 1 
1 1 ...
  $ mb   : num  131 125 131 119 136 138 139 125 131 134 ...
  $ bh   : num  138 131 132 132 143 137 130 136 134 134 ...
  $ bl   : num  89 92 99 96 100 89 108 93 102 99 ...
  $ nh   : num  49 48 50 44 54 56 48 48 51 51 ...
  $ year : num  -4000 -4000 -4000 -4000 -4000 -4000 -4000 -4000 -4000 
-4000 ...
 > table(Skulls$epoch)

4000BC 3300BC 1850BC  200BC  AD150
     30     30     30     30     30

This is what I've tried.  I reshape the data to a long format and can 
plot value ~ epoch or value ~ as.factor(year),
but I really want to space the boxplots according to the  numeric value 
of year.

# better variable labels -- how to incorporate these in the strip labels?
vlab <- c("maxBreadth", "basibHeight", "basialLength", "nasalHeight")

library(lattice)
library(reshape2)
Skulls$year <- rep(c(-4000, -3300, -1850, -200, 150), each=30)
sklong <- melt(Skulls, id=c("epoch", "year"))

bwplot(value ~ epoch | variable, data=sklong, scales="free",
     ylab="Variable value",
     xlab="Epoch",
     panel = function(x,y, ...) {
         panel.bwplot(x, y, ...)
         panel.linejoin(x,y, col="red", ...)
     }
     )

bwplot(value ~ as.factor(year) | variable, data=sklong, scales="free",
     ylab="Variable value",
     xlab="Year",
     panel = function(x,y, ...) {
         panel.bwplot(x, y, ...)
         panel.linejoin(x,y, col="red", ...)
     }
     )



-- 
Michael Friendly     Email: friendly AT yorku DOT ca
Professor, Psychology Dept.
York University      Voice: 416 736-5115 x66249 Fax: 416 736-5814
4700 Keele Street    Web:   http://www.datavis.ca
Toronto, ONT  M3J 1P3 CANADA



More information about the R-help mailing list