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

你离开我真会死。 提交于 2019-12-08 21:23:56

问题


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


回答1:


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")


来源:https://stackoverflow.com/questions/24082485/r-plot-a-centered-legend-at-outer-margins-of-multiple-plots

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!