R-plot a centered legend at outer margins of multiple plots

14,637

Option #1 is likely the route you should take, with xpd=NA. It does not automatically place the legend in the outer margins, but it allows you to place the legend anywhere you want. So, for example, you could use this code to place the legend at the top of the page, approximately centered.

legend(x=-1.6, y=11.6, legend=c("A", "B"), fill=c("red", "blue"), ncol=2, xpd=NA, bty="n")

I chose these x and y values by trial and error. But, you could define a function that overlays a single (invisible) plot on top of the ones you created. Then you can use legend("top", ...). For example

reset <- function() {
    par(mfrow=c(1, 1), oma=rep(0, 4), mar=rep(0, 4), new=TRUE)
    plot(0:1, 0:1, type="n", xlab="", ylab="", axes=FALSE)
    }

reset()
legend("top", legend=c("A", "B"), fill=c("red", "blue"), ncol=2, bty="n")
Share:
14,637
Ashwin
Author by

Ashwin

Computational biologist working in regulatory cancer genomics.

Updated on June 16, 2022

Comments

  • Ashwin
    Ashwin almost 2 years

    I want to plot a centered legend outside of the plotting area in a device having multiple plots. There has been many questions (with slight variations) asked in SO about changing the position of legend in a R plot.

    For example:

    1) R - Common title and legend for combined plots

    2) Common legend for multiple plots in R

    3) Plot a legend outside of the plotting area in base graphics?

    etc.

    Now what I understood from the above questions is that I got to set the option xpd = T or xpd = NAto plot legends at the outer margins. However when I try this, it somehow does not work for me ..

    par(mfrow=c(1,2),oma=c(0,3,0,0),xpd=TRUE)
    
    plot(c(5,10),col=c("red","blue"),pch=20,cex=2,bty="n",xlab="",ylab="")
    barplot(c(5,10),col=c("red","blue"))
    
    mtext(text="My two plots",side=3,cex=2,outer=TRUE,line=-3)
    
    legend("top",legend=c("A", "B"),fill=c("red","blue"),ncol=2,xpd=NA,bty="n")  # Option 1
    legend(x=0.01,y=11,legend=c("A", "B"),fill=c("red","blue"),ncol=2,xpd=TRUE,bty="n") # Option 2
    

    Now my question is, how does xpd exactly work ? as I am unable to figure out why shouldn't the legend not be placed outside the plot area with xpd=T.

    I apologize in advance if some consider this as a duplicate of the above questions !!

    Help is much appreciated

    Ashwin

  • Ashwin
    Ashwin almost 10 years
    Cool thanks.. is there anyway to automatically determine the x and y values or does that need to be determined by trail and error ??
  • Jean V. Adams
    Jean V. Adams almost 10 years
    You could use a workaround ... like overlaying one plot over the other two, so that you can then just call legend("top", ...). I'll add an example to my answer.