oldmar = par("mar")
draw_legend(
legend = "right!", ## default (other options incl, "left(!)", ""bottom(!)", etc.)
legend_args = list(title = "Key", bty = "o"),
lgnd_labs = c("foo", "bar"),
type = "p",
pch = 21:22,
col = 1:2
)
# The legend is placed in the outer margin...
box("figure", col = "cyan", lty = 4)
# ... and the plot is proportionally adjusted against the edge of this
# margin.
box("plot")
# You can add regular plot objects per normal now
plot.window(xlim = c(1,10), ylim = c(1,10))
points(1:10)
points(10:1, pch = 22, col = "red")
axis(1); axis(2)
# etc.
# Important: A side effect of draw_legend is that the inner margins have been
# adjusted. (Here: The right margin, since we called "right!" above.)
par("mar")
# To reset you should call `dev.off()` or just reset manually.
par(mar = oldmar)
# Note that the inner and outer margin of the legend itself can be set via
# the `lmar` argument. (This can also be set globally via
# `tpar(lmar = c(inner, outer))`.)
draw_legend(
legend_args = list(title = "Key", bty = "o"),
lgnd_labs = c("foo", "bar"),
type = "p",
pch = 21:22,
col = 1:2,
lmar = c(0, 0.1) ## set inner margin to zero
)
box("figure", col = "cyan", lty = 4)
par(mar = oldmar)
# Continuous (gradient) legends are also supported
draw_legend(
legend = "right!",
legend_args = list(title = "Key"),
lgnd_labs = LETTERS[1:5],
col = hcl.colors(5),
gradient = TRUE ## enable gradient legend
)
par(mar = oldmar)
Run the code above in your browser using DataLab