[R] Little graph questions!

David Brahm
Tue, 19 Feb 2002 18:35:19 -0000

Paul Johnson <pauljohn at ku.edu> wrote:
> I have had trouble positioning text in figures.  Because I don't know
what
> the plotted values will be until the model is run, it is hard to write
> coordinates for text(x,y,""). I frequently wish there were a way
to say "top
> left part of graph"...

As several people have replied, you need par("usr").  Here's a
simple function
that does it for you.  You pass "absolute" coordinates xa and ya in
the range
[0,1], and it returns the user coordinates you need for "text",
"legend", etc.:
-------------------------------------------------------------------------------
g.coord <- function(xa, ya, u=par("usr")) {
  z <- list(x=u[1]+xa*(u[2]-u[1]),  y=u[3]+ya*(u[4]-u[3]))
  if (par("xlog")) z$x <- 10^z$x;  if (par("ylog")) z$y
<- 10^z$y
  z
}
-------------------------------------------------------------------------------

To put text near the top left (but 2% in from the edges), type:
  R> text(g.coord(.02,.98), "Hello", adj=c(0,1))

One subtlety: text() somehow recognizes that its first argument is a list(x,y),
and its second argument is therefore the "labels" to print.  However,
this
recognition fails if you use plotmath.  So this doesn't work:
  R> text(g.coord(.02, .98), quote(x==5), adj=c(0,1))    # Fails
but the solution is simple: you just need to name the "labels"
argument:
  R> text(g.coord(.02, .98), l=quote(x==5), adj=c(0,1))  # OK
(Note that's the letter "l", short for "labels".)
--
                              -- David Brahm (brahm at alum.mit.edu)