[R] Keeping lattice plot axes in the same place when legend sizes vary
wayne.rochester at csiro.au
Mon Jan 3 09:27:44 CET 2011
I am generating a number of lattice plots with common axes but varying
legends. There is one plot in the window at a time. I would like the
plot axes to always appear in the same place within the window (and
saved images) so the plots do not move around when they are combined in
a video or browsed in something like an HTML document.
The default behaviour of the lattice package is to centre the whole
plot, including the legend, in the window. If a legend is on the right
and gets bigger from one plot to the next (e.g. due to bigger numbers),
then the graph axes shift left a little to keep the centre of the whole
plot in the same place.
To prevent this, is it possible to explicitly set the position of the
axes? Alternatively, being able to align the plot with the left of the
window rather than the centre would also provide a solution (when the
legend is on the right).
The following example demonstrates the default behaviour:
x <- -10:10
y <- -10:10
grid <- expand.grid(x=x, y=y)
grid$z <- grid$x * grid$y
print(levelplot(z ~ x * y, data=grid, aspect=1))
The example plots a graph with a legend on the right. A wide window is
used to provide horizontal space to enable to legend to grow or shrink
without affecting the size of the graph axes. The whole plot, including
the legend, is centred horizontally. If we run the same code, but with
grid$z multiplied by 10, then the legend is a little wider, and the
graph axes are shifted a little to the left.
I had a play with the grid viewport functions, but was only able to
change the size and position of the viewport the graph went into rather
than the position of the graph within that viewport.
CSIRO, Brisbane, Australia
More information about the R-help