[R] Plotting a legend outside the figure - units

From: <rhelp.20.trevva_at_spamgourmet.com>
Date: Mon, 18 Feb 2008 10:53:54 +0100

Dear R gurus,

I am trying to plot a legend in the margins of a figure. The basic idea is to have two (or more) plots on the same figure, but then to have a common legend at the bottom of the plot. The approach that I have taken is to setup the figures, then do a "dummy" plot of the legend to determine the height of the legend box (ie from the value returned by the legend() command). I then use this height to adjust the outer margin of the plot to make sufficient space for the legend. After plotting the actual plots, I then finally plot the legend, moving it down to the bottom using the inset option in legend().

The problem is a question of units. I have not been able to find what units legend() returns anywhere in the documentation (ie in rect$h) - I've made the asumption that its inches, but that may not necessarily be correct. Similarly, the inset option to legend() requires units equal to a fraction of the plot size, but I'm not exactly sure how to make that line up with what I get out of legend().

Suggestions and insights most welcome! Code follows at the bottom.



#First set number of plots


#Generate the legend once to get the height
leg <- legend("bottom",legend=c("Item A","Item B"),horiz=TRUE,pch=c(1,2),



#Add space at the bottom for the legend
bottom.spacing <- par("omi") + c(leg$rect$h,0,0,0) par(omi=bottom.spacing)

x <- runif(100)
y <- runif(100)
z <- rnorm(100)

plot(x,y,xaxt="n",xlim=c(0,1),xlab="",pch=1,col="red") plot(y,z,xlim=c(0,1),pch=2,col="blue")

#Actually plot legend this time - inset value is done manually by trial
#and error, but obviosuly I'd rather have this done intelligently
legend("bottom",legend=c("Item A","Item B"),horiz=TRUE,pch=c(1,2),


R-help_at_r-project.org mailing list
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. Received on Mon 18 Feb 2008 - 11:23:43 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Mon 18 Feb 2008 - 12:30:14 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive