Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
220 views
in Technique[技术] by (71.8m points)

R plot: Insert text in the middle of device region when showing multiple plots

I have a plot with a 4x3 format, however only 10 plots are shown.

par(mfrow=c(4,3)) #Grid layout

Now I want to insert one legend for all! plots in the middle of the complete device region and at the far right corner another text for some info. However right now with this code, the legend is in the middle of the last(!) small plot and the text at the far right corner of the last plot. How can I move them both into the middle of my device?

  #Legend
  par(xpd=NA)
  legend(legend="Legend", col=hblue,lty=1, lwd=2, bty="n", text.col="black", ncol=1, "bottom", 
         inset = c(0.0, -.1),cex=0.65) 

  #Inserting the source of data
  text_note=paste("Source:")
  mtext(text_note ,cex=0.4,col=hgrey,side = 1, line = 4, outer = FALSE,padj=0,adj=1)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

resulting plot

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...