[R] help with legend()
Paul Murrell
p.murrell at auckland.ac.nz
Mon Oct 20 00:44:08 CEST 2003
Hi
Deepayan Sarkar wrote:
> On Friday 17 October 2003 02:20, Martin Maechler wrote:
>
>>>>>>>"PaulSch" == Schwarz, Paul <paul.schwarz at oregonstate.edu>
>>>>>>> on Wed, 15 Oct 2003 12:09:11 -0700 writes:
>>>>>>
>> PaulSch> I am converting some S-PLUS scripts that I use for
>> PaulSch> creating manuscript figures to R so that I can take
>> PaulSch> advantage of the plotmath capabilities. In my
>> PaulSch> S-PLUS scripts I like to use the key() function for
>> PaulSch> adding legends to plots,
>>
>>AFAIK key() in S+ is from the trellis library section.
>>The corresponding R package, trellis, has
>
> ^^^^^^^
> lattice, actually :-)
>
>
>>a draw.key() function that may work similarly to S-plus' key()
>>{Deepayan ?}.
>
>
> That's correct. Of course, the S-PLUS key() works wih non-trellis graphs as
> well, whereas draw.key() will produce a grid object and hence work with grid
> graphics only. (I haven't checked Paul's new gridBase package, that may
> enable using this for base graphics as well.)
gridBase makes it possible, although it takes a little bit of work.
Here's a simple example.
## First a standard base plot (mangled example from lattice):
data(OrchardSprays)
attach(OrchardSprays)
tmt <- sort(as.numeric(treatment))
dec <- decrease[order(as.numeric(treatment))]
row <- rowpos[order(as.numeric(treatment))]
plot(tmt, dec, type="n")
for (i in unique(row)) {
subset <- row == i
lines(tmt[subset], dec[subset], col=i)
}
## Now load lattice (to produce the key) and gridBase (to combine the
## lattice key with the base plot):
library(lattice)
library(gridBase)
## Align grid viewports with base plot:
par(new=TRUE)
vps <- baseViewports()
push.viewport(vps$inner, vps$figure, vps$plot)
## Create lattice key:
key <- draw.key(list(lines = list(col=1:8),
text =
list(lab=as.character(unique(OrchardSprays$rowpos))),
columns = 4, title = "Row position",
background=par("bg"),
border=TRUE))
## Use a grid viewport to position the key 3mm in from the top-left
## corner of the plot (NOTE this doesn't quite work properly -- the
## width and height of the key are not calculated correctly
## [Deepayan: It's an error in grid and I'm working on a fix]):
push.viewport(viewport(x=unit(3, "mm"), y=unit(1, "npc") - unit(3,"mm"),
width=unit(1, "grobwidth", key),
height=unit(1, "grobheight", key),
just=c("left", "top")))
grid.draw(key)
# This just shows where the viewport is
# and shows how it is too big for the key
grid.rect(gp=gpar(col="grey"))
## Clean up:
pop.viewport(4)
Paul
--
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