[R] Resizing a graph with a legend in the outer margin - wish for functionality like mtext()

Paul Murrell paul at stat.auckland.ac.nz
Wed Mar 25 22:56:14 CET 2015


Hi

You can use the recordGraphics() function for this (if you are careful).
For example ...

x <- 1:100
y <- x +rnorm(100, 0,10)
plot(x,y, xlab="", main="Shrink and Enlarge This Graph")
abline(0,1 ,lty=2)

recordGraphics(
     {
         legend(x=grconvertX(1, from = "ndc", to = "user"),
                y=grconvertY(0, from = "ndc", to = "user"),
                lty=2,
                legend="The legend scales nicely!",
                xjust=1, yjust=0,
                bty="n",
                xpd=TRUE)
     },
     list(), getNamespace("graphics"))

mtext("This example has some text in the outer margin.\nIt rescales 
nicely.",
       side = 1, line=3.5, adj=0)


The important result is that those grConvert*() calls are performed on 
every redraw.

Paul

On 03/26/15 07:21, Peter Lomas wrote:
> Dear R-Helpers
>
> I am attempting to get a legend in the outer margins of a graph that has a
> similar flexibility to mtext(), within base graphics.  This is used in a
> tool that will end up with graphs of many different coordinates, exported
> in many different sizes.  I'm trying to come up with a general solution.
> I've used "bottom right" before but I found it interferes with the graphs
> frequently.
>
> Here was my best attempt at something general, but then I encountered the
> graph re-sizing issue:
>
> x <- 1:100
> y <- x +rnorm(100, 0,10)
> plot(x,y, xlab="", main="Shrink and Enlarge This Graph")
> abline(0,1 ,lty=2)
>
> legend(x=grconvertX(1, from = "ndc", to = "user"),
>         y=grconvertY(0, from = "ndc", to = "user"),
>         lty=2,
>         legend="The legend doesn't rescale nicely",
>         xjust=1, yjust=0,
>         bty="n",
>         xpd=TRUE)
>
> mtext("This example has some text in the outer margin.\nIt rescales
> nicely.",
>        side = 1, line=3.5, adj=0)
>
>
> Thanks!
> Peter
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> 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