# [R] grid.pack and grid.frame bewilder me

Paul Murrell p.murrell at auckland.ac.nz
Thu Nov 10 21:49:48 CET 2011

```Hi

On 11/11/2011 7:00 a.m., cheung zihong wrote:
> Hello R friends,
>
> I get quite confused in using the grid graphic function grid.pack( )
> and grid.frame ( ). Here is a simple example:
>
>   library(grid)
>   grid.frame(name="frame1")
>   grid.pack("frame1",rectGrob(width=unit(0.5,"npc"),
> height=unit(0.5,"npc"), gp=gpar(col="red")))
>
> what I expect is a rectangle with half the default device's
> dimensions,but it returns a rectangle like 1/4 of the device.why?
> In addition  wonder what the rectGrob is referred to if there are x.y arguments.

The problem is that the "cell" that you are packing the rectangle into
is getting its own size from the rectangle.  That makes sense if the
rectangle has an absolute size (e.g., unit(1, "inches")), but if the
size of the rectangle is relative it creates a bit of havoc.  The
conversation between the cell and the frame goes a bit like this ...

frame to cell:  how big are you?
cell to frame:  I dunno, I'll ask my rectangle
cell to rectangle:  how big are you?
rectangle to cell:  I'm half as big as my parent
cell to frame:  I'm half as big as my parent

Now the cell is half as big as the frame and the rectangle is half as
big as the cell!

You can get what I think you want like this (tell the cell how big it is
within the frame, rather than leaving it to ask its rectangle) ...

library(grid)
grid.frame(name="frame1")
grid.pack("frame1",
width=unit(1, "null"),
height=unit(1, "null"),
rectGrob(width=unit(0.5,"npc"),
height=unit(0.5,"npc"), gp=gpar(col="red")))

No, that's not the greatest software design in history, but judging from
your next question I'm not sure that you need to use frames and packing.
It is more often the case that you can get what you want by using
viewports and layouts directly.

Hope that helps.

Paul

>   Another question is  I want to pack several barplots of different
> sizes in a row by average space,but the grid.pack just didn't work
> out, which gave me  a layout that the the space between the midlines of
> each figure equals,not between their bounders. I have been working on
> this for  a couple of days with more confusion.
>
>   I hope someone can help me out.  I will  greatly  appreciate it.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

--
Dr Paul Murrell
Department of Statistics
The University of Auckland
Private Bag 92019
Auckland
New Zealand
64 9 3737599 x85392
paul at stat.auckland.ac.nz
http://www.stat.auckland.ac.nz/~paul/

```

More information about the R-help mailing list