Question

I am concatenating multiple plots into one figure (24 to be specific) and I can't quite figure out how to add a legend for the whole figure.

par(mfrow = c(4,6))

for(i in 1:24){
x <- rep(0,3)
y <- rnorm(3, 3)
par(family = "Garamond")
col_vec <- c( "darkblue", "gray65", "maroon4")
plot(x,y, xaxt = 'n', xlab = '', ylab = '', xaxt='n', bty = "n",  ylim = c((min(y) - 1.5),(max(y) + 1.5)),  col = col_vec, pch = 19, cex =.8)
abline(h=y[2], lty=2, col = "gray89")}

title("Effect Size", outer = TRUE, line = -2, cex = 2)  
legend("topleft", c("Treatment 1", "Control", "Treatment 2"), col = col_vec, pch = 15)

If anybody knows how to add the legend to the lefthand side rather than each plot or all of the plots, that would be great; note that without the legend command, the code above produces the following figure:

enter image description here

Was it helpful?

Solution 2

Here's one suggestion with ggplot2

library(plyr)
xy <- rdply(24, data.frame(x=0, y=rnorm(3,3), id=1:3))

library(ggplot2)

ggplot(xy, aes(x, y, colour=factor(id))) + 
  facet_wrap(~.n, scales="free", ncol=4) +
  geom_point() + 
  annotate("segment", x=-0.1, xend=-0.1, y=-Inf, yend=+Inf) +
  scale_x_continuous(breaks=NULL, expand=c(0,0), lim=c(-0.1, 0.1)) +
  scale_y_continuous(expand=c(0,0.1)) +
  theme_minimal() + 
  theme(strip.text.x = element_blank(),
        axis.title.x = element_blank(),
        axis.title.y = element_blank()) +
  scale_colour_manual("", labels=c("Treatment 1", "Control", "Treatment 2"),
                      values=c( "darkblue", "gray65", "maroon4"))

enter image description here

OTHER TIPS

For base graphics I would suggest using layout instead of par(mfrow=c(4,6)). That way you can leave yourself additional room to place the legend, use plot.new() to move to the final panel area and place the legend there.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top