如何在 R 中绘制图例而不是每个 window 绘制多个图

How to plot legend in place of a plot multiple plots per window in R

我想为我的三个地块放置一个共同的图例,放在第四个地块所在的位置(以黄色突出显示)。我该怎么做?

重现情节的代码

par(mfrow = c(2, 2))

x <- rep(1:9, 3)
y <- sample(1:9, 27, replace = T)
group <- rep(1:3, each = 9)

for(i in 1:3){
  plot(x = x, y = y, type = "n")
  for(j in 1:3){
    print(c("red", "blue", "green")[group])

    lines(x = x[group == j],
          y = y[group == j],
          col = c("red", "blue", "green")[j])
  }
}

您可以在最后一个方块中绘制一个“空白”图,然后在顶部绘制图例

for(i in 1:3){
  plot(x = x, y = y, type = "n")
  for(j in 1:3){
    print(c("red", "blue", "green")[group])
    
    lines(x = x[group == j],
          y = y[group == j],
          col = c("red", "blue", "green")[j])
  }
}
plot(0, 0, type = 'l', bty = 'n', xaxt = 'n', yaxt = 'n', xlab="", ylab="")
legend('center',
  legend = c("Red", "Blue", "Green"), 
  col = c("red","blue", "green"), 
  lwd=1, xpd = TRUE, cex = 1, seg.len=1, bty = 'n')