Brigadeiro
Brigadeiro

Reputation: 2945

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

I want to place a common legend for my three plots in the slot where the fourth plot would go (highlighted in yellow). How can I do this?

Code to reproduce plots

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])
  }
}

enter image description here

Upvotes: 1

Views: 107

Answers (1)

MrFlick
MrFlick

Reputation: 206486

You can draw a "blank" plot in the last square and then draw the legend on top

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

plot in layout

Upvotes: 2

Related Questions