tags:

views:

466

answers:

1

We are currently using R to automatically generate various kinds of boxplots. The problem we have is that the length our labels varies considerably between different plots and classes in one plot.

Is there a way to automatically adjust the plot so that all the labels will fit it nicely? Specifying a worst case mar isn't feasible because in some plots the labels are considerably shorter than in others.

A: 

Lattice is the graphics library most likely to be helpful here. I say that for two reasons: (i) lattice is based on the grid system, and by accessing grid's graphical primitives, you can get much finer control over, among other things, the location of your panel output; and (ii) there's more to work with--the R standard graphics package has 70 different parameters, while Lattice has 371--by my count anyway, (length(names(unlist(trellis.par.get())))), yet those 371 are not in a flat structure like they are in the base package, but instead are collected in a hierarchical structure (with 30 or so parameter groups at the top level).

What you want is relative positioning of your axis labels. I would recommend going down one level for this sort of task. So to do what you want, just change the relevant grob slots then just redraw the two grobs (using the R interactive prompt):

library(lattice)
library(grid)
bwplot(~runif(200, 10, 99), xlab="x-axis label", ylab="y-axis label")
# move the x-axis label to the far left
grid.edit("[.]xlab$", grep=T, x=unit(0, "npc"), just="left", redraw=T)
# move it to the far right
grid.edit("[.]xlab$", grep=T, x=unit(1, "npc"), just="right", redraw=T)
# move it to the center
grid.edit("[.]xlab$", grep=T, x=unit(0.5, "npc"), just="center", redraw=T)
# same for y-axis
grid.edit("[.]ylab$", grep=T, y=unit(0.5, "npc"), just="center", redraw=T)

"[.].xlab$", grid.edit takes a gPath object (just a path traversing a gTree, which is just a grob that contains other grobs); because i didn't know where in the gPath my object of interest resides (the x-axis/y-axis label, i used a regular expression form for the object;

"grep=T", just tells grid.edit to treat the previous parameter as a regular expression;

"x=unit(0.5, 'npc')", specifying viewport coordinates here (in this case, just the x value); 'npc' ('normalized parent coordinates', which is the default) treats the viewport origin as (0,0), and assigns it a width & height of 1 unit each. Hence, i've specified the center of the viewport along the x axis.

doug