Hi
Here's one way to do it:
fitText <- function(text) {
tw <- convertWidth(stringWidth(text), "inches", valueOnly=TRUE)
vw <- convertWidth(unit(1, "npc"), "inches",
valueOnly=TRUE)
cex <- vw/tw
grid.text(text, gp=gpar(cex=cex))
}
pushViewport(viewport(layout = grid.layout(5, 2, c(9,1), 1:5)))
for (i in 1:5) {
pushViewport(viewport(layout.pos.row = i, layout.pos.col = 1))
pushViewport(viewport(x = 0, width = i/5, height = .8, just =
"left"))
grid.rect(gp = gpar(fill = rainbow(5)[i]))
grid.yaxis(main = F)
fitText("I am some descriptive text.")
popViewport()
popViewport()
}
This should be ok for producing a fixed-size graphic, but if you change
the size of the device (e.g., resize the window), the calculations will
become incorrect. There are ways around that; let me know if you want
to know more.
Paul
kevin bartz wrote:> Hello! I first would like to compliment the authors of grid on what has
been
> a wonderfully useful package for me. Now, my question: Is there any way I
> can specify the size of some grid.text using grid units?
>
> I must label the regions of a plot. The regions can be either very small or
> very large, so I would like to label each by fitting its text to the size
of
> the region in question. Ideally, I could have nice, big text labeling the
> big regions and tiny type in the small regions.
>
> Let me try to illustrate my scenario. Imagine that my plot looks like this:
>
> pushViewport(viewport(layout = grid.layout(5, 2, c(9,1), 1:5)))
> for (i in 1:5) {
> pushViewport(viewport(layout.pos.row = i, layout.pos.col = 1))
> pushViewport(viewport(x = 0, width = i/5, height = .8, just =
"left"))
> grid.rect(gp = gpar(fill = rainbow(5)[i]))
> grid.yaxis(main = F)
> grid.text("I am some descriptive text.")
> popViewport()
> popViewport()
> }
>
> Unfortunately, the descriptive text overlaps with the axis for the red
> rectangle! Is there any way, given the dimensions of some region on the
grid
> and the desired text, that I can fit this text to the region?
>
> Sorry if I missed something in the documentation. I really did look at
> ?grid.text, all the documentation for the grid package, all the PDFs posted
> on the grid page as well as previous r-help postings, but none seemed to
> address this question. Thanks so much for any help you can provide!
>
> Kevin
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide!
http://www.R-project.org/posting-guide.html
--
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/