2012-04-17 51 views
4

這可能是一個老問題,但我無法在任何地方找到令人滿意的答案。假設我有以下代碼:將圖例添加到多個for循環圖的邊距

par(mfrow = c(2,1), mar = c(4,4,1,1), oma=c(2,2,2,2)) 
stuff <- c("ed", "bla") 
cols <- c("red", "blue") 
for(i in 1:length(stuff)) { 
x <- rnorm(10,3,2) 
y <- seq(1,10) 
plot(x,y, type = "o", col = cols[i], xlab = paste("stuff about", stuff[i]))} 
legend("bottomright", legend = stuff, col = cols, lwd = 1, bty = "n") 
par(mfrow=c(1,1)) 
title(main = "ed & bla", outer = T) 
mtext("This is a plot", 3, line=0.5, adj=1.0, cex=1, outer=TRUE) 

如何在圖的底部邊距中添加圖例?

enter image description here

+0

要麼使用'佈局()'或'帕(mfrow = C(2,1))'。 (參見參數中的例子)'legend'應該繪製在最後一個繪圖內 – 2012-04-17 20:48:16

+1

你可以把圖例放在循環內,但是如果它是最後一次迭代,只繪製它:'if(i == length(stuff) ){傳說(...)}'。 – 2012-04-17 23:11:12

+0

沒想過。很有幫助。感謝文森特! – Mikko 2012-04-18 20:25:25

回答

3

重新排列情節的要求,讓你立刻繪製傳說中的最後情節(外循環),但接下來的修改劇情參數之前後。請注意,只有「圖例」命令已被移動:

par(mfrow = c(2,1), mar = c(4,4,1,1), oma=c(2,2,2,2)) 
stuff <- c("ed", "bla") 
cols <- c("red", "blue") 
for(i in 1:length(stuff)) { 
x <- rnorm(10,3,2) 
y <- seq(1,10) 
plot(x,y, type = "o", col = cols[i], xlab = paste("stuff about", stuff[i]))} 
legend("bottomright", legend = stuff, col = cols, lwd = 1, bty = "n") 
par(mfrow=c(1,1)) 
title(main = "ed & bla", outer = T) 
mtext("This is a plot", 3, line=0.5, adj=1.0, cex=1, outer=TRUE) 

這將圖例置於底部圖的右下方。

+0

Mhh ..謝謝!任何想法如何將圖例放在最後一幅圖的外邊緣? – Mikko 2012-04-18 17:35:00

0

但你要設置的座標manualy

par(mfrow = c(2,1), mar = c(4,4,1,1), oma=c(2,2,2,2)) 
stuff <- c("ed", "bla") 
cols <- c("red", "blue") 
for(i in 1:length(stuff)) { 
    x <- rnorm(10,3,2) 
    y <- seq(1,10) 
    plot(x,y, type = "o", col = cols[i], xlab = paste("stuff about", stuff[i]))} 
legend(y=-5, x=5, legend = stuff, col = cols, lwd = 1, bty = "n", xpd=NA)