R square plot side by side

Viewed 28

I want to show sevaral plots in square side by side in R, e.g., six plots in par(mfrow=c(3,2)). I find here that one can make square axes in R by par(pty="s") and asp=1, then I try

### data
x1 <- 1:6; y1 <- 1:6
x2 <- 1:6; y2 <- 1:6
x3 <- 1:6; y3 <- 1:6
x4 <- 1:6; y4 <- 1:6
x5 <- 1:6; y5 <- 1:6
x6 <- 1:6; y6 <- 1:6

### title
t1 <- 'title1'
t2 <- 'title2'
t3 <- 'title3'
t4 <- 'title4'
t5 <- 'title5'
t6 <- 'title6'

### plot
par(mfrow=c(3, 2))
par(pty="s"); asp=1 # square plotting
plot(x1, y1, pch=16, xlim=c(0, 8), ylim=c(0, 8), asp=asp, ann=F, xaxt='n', yaxt='n')
abline(a=0, b=1)
mtext(side=1, line=2, t1)
plot(x2, y2, pch=16, xlim=c(0, 8), ylim=c(0, 8), asp=asp, ann=F, xaxt='n', yaxt='n')
abline(a=0, b=1)
mtext(side=1, line=2, t2)
plot(x3, y3, pch=16, xlim=c(0, 8), ylim=c(0, 8), asp=asp, ann=F, xaxt='n', yaxt='n')
abline(a=0, b=1)
mtext(side=1, line=2, t3)
plot(x4, y4, pch=16, xlim=c(0, 8), ylim=c(0, 8), asp=asp, ann=F, xaxt='n', yaxt='n')
abline(a=0, b=1)
mtext(side=1, line=2, t4)
plot(x5, y5, pch=16, xlim=c(0, 8), ylim=c(0, 8), asp=asp, ann=F, xaxt='n', yaxt='n')
abline(a=0, b=1)
mtext(side=1, line=2, t5)
plot(x6, y6, pch=16, xlim=c(0, 8), ylim=c(0, 8), asp=asp, ann=F, xaxt='n', yaxt='n')
abline(a=0, b=1)
mtext(side=1, line=2, t6)

However, the final entire plot gives large space among the sub-plots. How to show the plots side by side tightly?

1 Answers

Your code is fine, the device size just needs to be set rightly. Use a different device such as png() or pdf() with fixed dimensions and choose them clever.

Also, you may loop over your data instead of repeating code.

xlst <- list(1:6, 1:6, 1:6, 1:6, 1:6, 1:6)
ylst <- list(1:6, 1:6, 1:6, 1:6, 1:6, 1:6)
tlst <- list("title1", "title2", "title3", "title4", "title5", "title6")

png(filename='plot.png', width=400, height=600)  ## open device

op <- par(mfrow=c(3, 2), pty="s")
lapply(1:6, \(i) {
  plot(xlst[[i]], ylst[[i]], pch=16, xlim=c(0, 8), ylim=c(0, 8), asp=1, ann=F, xaxt='n', yaxt='n')
  abline(a=0, b=1)
  mtext(side=1, line=2, tlst[[i]])
})
par(op)

dev.off()  ## close it

enter image description here

If you use Rstudio you could also try to rescale the "Plots" window with your mouse. However, stuff like legends, axis labels, etc. might get distorted which is why I recommend to use another device.

Related