Sunday, 18 August 2013

Drawing of a legend via grid: No grid object drawn

Drawing of a legend via grid: No grid object drawn

I would like to use grid/gridBase to add a legend to a base graphics. The
following minimal example already contains the first steps towards the
legend (certainly not correct yet), but the legend is not shown. Some
problem with units (?)
myplot <- function(x=1:10)
{
stopifnot(require(grid), require(gridBase))
## layout
opar <- par(no.readonly=TRUE); on.exit(par(opar))
plot.new()
gl <- grid.layout(nrow=2, ncol=3, widths=c(0.1, 0.8, 0.1),
heights=c(0.8, 0.2),
default.units="npc")
pushViewport(viewport(layout=gl))
## points
pushViewport(viewport(layout.pos.row=1, layout.pos.col=2))
par(plt = gridPLT())
par(new=TRUE)
plot.window(xlim=c(1, 10), ylim=c(1, 10))
plot(x, rev(x), col="blue", type="b")
lines(x, x, col="red", type="b")
popViewport()
## legend
pushViewport(viewport(layout.pos.row=2, layout.pos.col=2))
legend <- c("type1", "type2")
cl <- c("blue", "red")
grid.draw(
gTree(pointsGrob(x=1:2, y=c(0.5, 0.5), name="points",
gp=gpar(col=cl, cex=0.55)),
textGrob(legend, just="left", name="text"),
name="legend")
)
popViewport()
## return
invisible(gl)
}
myplot()

No comments:

Post a Comment