[R] plot legend from file

Jim Lemon
Thu, 05 Nov 2009 11:40:23 -0000

On 11/05/2009 09:10 PM, Kim Vanselow wrote:
> Dear r-helpers,
> I want to plot a legend (using legend())into an ordination plot (nmds
produced by vegan/metaMDS). I used the output of a cluster analysis to create
groups. I created a new .csv-file with 2 columns, one with the site ID used in
the ordination, one with the group label derieved from the cluster dendrogram. I
used this file to display the site-labels in differnt group-specified colours
(using col=groupfile$grouplabel). This works. But now I want to create a legend
with these groups and groupcolours from this file. I did not find anything in
tutorials or help files about this. Maybe you have an idea?
> Thank you very much
> Kim
>
Hi Kim,
Unless this plot is greatly different from others, you first need to
know where you can put the legend. You can get the device limits in user
coordinates from this function:

devUsr<-function() {
  usrcoord<-par("usr")
  plotin<-par("pin")
  devin<-par("din")
  plotmar<-par("mar")
  xcess<-(usrcoord[2]-usrcoord[1])*(devin[1]/plotin[1]-1)
  ycess<-(usrcoord[4]-usrcoord[3])*(devin[2]/plotin[2]-1)
  devusr<-usrcoord+c(-xcess*plotmar[2]/(plotmar[2]+plotmar[4]),
   xcess*plotmar[4]/(plotmar[2]+plotmar[4]),
   -ycess*plotmar[1]/(plotmar[1]+plotmar[3]),
   ycess*plotmar[3]/(plotmar[1]+plotmar[3]))
  return(devusr)
}

Your legend must be displayed within these coordinates. If you want it
to extend beyond the plot, you must do this:

par(xpd=TRUE)

before the legend command. Then you should be able to use legend,
probably using the "fill" argument to show the colors. Remember to:

par(xpd=FALSE)

when you have drawn the legend if it extends outside the plot.

Jim