[R] legend()

Marc Schwartz marc_schwartz at comcast.net
Tue Jul 31 21:04:47 CEST 2007

On Tue, 2007-07-31 at 10:21 -0700, amna khan wrote:
> Hi Sir
> How can I use legend() outside th e plot.
> Please guid in this regard.
> Thanks

Create a plot, specifying outer margins to make space for the legend.
Then move the legend to the open region.

# Set 'xpd' to NA so that the legend is not clipped
# at the plot region, which it is by default
par(xpd = NA)

# Make some room at the right hand side
par(oma = c(0, 0, 0, 10))

# Do the plot

# Do the legend and use 'inset' to move the legend to
# the right hand outer margin
legend("topright", legend = 1:5, inset = c(-.4, .0))

You can adjust the outer margin settings and the 'inset' value as you
may require to make room for the legend on the side required.

See ?par and ?legend for more information.

Another option would be to use layout() to create more than one plot
region, perhaps adjusting the heights and/or widths of the plot regions,
such that the data plot goes into one region and the legend into the
other.  See ?layout for more information.


Marc Schwartz

More information about the R-help mailing list