With using par(mfrow)
you are slicing up the device region for each plot so it can be difficult to get to regions outside of where you currently are and you need to fill the plot regions in order. Here's a strategy using layout
and outer margins.
First, I use layout()
to specify the order i want to create the plots, I leave the center square for the end so i can create the legend last. Then i create a blank plot window and add just the legend.
To get the floating text, I use the outer margin region. I use par(oma=c(2,0,0,0))
to request some extra room at the bottom of the plotting area, then I use mtext()
to add the text to that outer margin region outside of any individual plot. Here's the code.
par(oma=c(2,0,0,0))
layout(matrix(c(1,2,3,4,9,5,6,7,8), byrow=T, ncol=3))
for(i in 1:8) {
plot(1:10, runif(1:10), main=paste("plot", i))
}
plot.new()
plot.window(0:1, 0:1)
legend("center","center", c("Apples","Oranges"), col=c("red","orange"), pch=20)
mtext("source", side=1, outer=T, adj=.9)
And here is the output.
If you just wanted the text in the center with the legend, you can forget about the outer margins and the mtext
and just use
text(.5,0, "Source")
right after the call to legend()
. That will add the text at the bottom center of the middle plot.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…