0

I have a multi-panel lattice figure. It has an even number of equal-width columns. I would like to center text across the columns.

Sometimes, this is easy to do. For example, the xlab and main arguments often handle this job nicely. But I want a more flexible solution. (I have many strings and want to position them at different heights, but always centered across the columns.)

grid.text("Label", x = unit(.5, "npc"), y = unit(yPos, "npc")) will work when the figure has no annotations outside the panel. But when it does -- for example, when I use the scales argument to create row labels -- using grid.text() in this way doesn't center the text. Here is a minimal example:

dataToPlot <- data.frame(x = 1:2, y = 1:2, panel = c('a', 'b'))
plot1 <- xyplot(
  y ~ x | panel, 
  data   = dataToPlot,
  layout = c(2,1),
  ylab   = '',
  xlab   = '',
  scales = list(
    x = NULL, 
    y = list(
      draw   = TRUE,
      labels = c("Label 1", "Label 2"),
      at     = c(1.8, 1.4))))
print(plot1)
grid.text("XXX", x = unit(.5, "npc"))

The "XXX" isn't centered. How can I center it?

I suppose that I could draw the figure without the row labels (i.e., without supplying a scales argument), use grid.text("Label", x = unit(.5, "npc"), y = unit(yPos, "npc")), and then use grid.text() again to draw the row labels. But is there a simpler solution?

user697473
  • 2,165
  • 1
  • 20
  • 47

2 Answers2

1

You can navigate the viewport tree and place a grob in the grid layout,

plot1
seekViewport("plot_01.toplevel.vp")
grid.text("centred\ntext", gp=gpar(col="red"), 
          vp=viewport(layout.pos.row=9, layout.pos.col=9:13))

enter image description here

baptiste
  • 75,767
  • 19
  • 198
  • 294
  • Thank you -- this is most helpful. But in a general sense, I am still not sure of how to center text. For example, in your code above, you center by using `vp=viewport(layout.pos.row=9, layout.pos.col=9:13)`. In different figures, the `layout.pos.row` and `layout.pos.col` arguments will need to be different. How can I figure out what they should be? (I suppose that this is like asking: how can I learn the layout of "plot_01.toplevel.vp"?) – user697473 Aug 24 '13 at 18:33
  • 1
    the best way, I find, is to read the lattice source code every night before going to bed. `showViewport()` might be of some help too. – baptiste Aug 24 '13 at 18:49
  • `trellis.focus` might be useful too – baptiste Aug 24 '13 at 19:33
0

Paul Murrell provides this answer, which seems to work regardless of the layout (in terms of rows and columns of panels) of the plot:

downViewport("plot_01.figure.vp")
grid.text("centred\ntext")
user697473
  • 2,165
  • 1
  • 20
  • 47