0

I am learning how to use R to creating multiple plots with a loop, putting them on one plot (or "canvas") and saving the plot. I want the plot to be 2x2. This is the tutorial I am following: https://bookdown.org/ndphillips/YaRrr/creating-multiple-plots-with-a-loop.html

Here is my code:

library(yarrr)

# Create the loop.vector (all the columns)
loop.vector <- 1:4

png(file="saving_plot2.png",
    width = 1500, height = 1200)
par(mfrow = c(2, 2))  # Set up a 2 x 2 plotting space
for (i in loop.vector) { # Loop over loop.vector
  
  # store data in column.i as x
  x <- examscores[,i]
  
  # Plot histogram of x
  hist(x,
       main = paste("Question", i),
       xlab = "Scores",
       xlim = c(0, 100))
}
dev.off()

The plot looks decent, but is there a way to control/increase space between the subplots and add a main title to the top of this plot? I know when creating one plot in base R, you would use: par(mar=c(5,4,4,2) + 0.1), but I am already using par() here.

Woj
  • 449
  • 1
  • 5
  • 15

1 Answers1

0

mar and title are easy ways to do this. Mar changes spacing of a plot and title sets a title:

library(yarrr)

loop.vector <- 1:4

png(file="saving_plot2.png",
    width = 1500, height = 1200)

# Mar changes the spacing of each plot from bottom, left, top, right
par("mar"=c(3,4,4,2), mfrow = c(2, 2))  # Set up a 2 x 2 plotting space
for (i in loop.vector) { # Loop over loop.vector
  
  # store data in column.i as x
  x <- examscores[,i]
  
  # Plot histogram of x
  hist(x,
       main = paste("Question", i),
       xlab = "Scores",
       xlim = c(0, 100))
}

# Sets the title
title("This is a title", line = -1, outer = TRUE)

dev.off()

There's actually a number of ways to get a chart like what you're looking for. See the below links for multiple solutions and explanations:

Common title:

Common main title of a figure panel compiled with par(mfrow)

Increase Spacing:

Add extra spacing between a subset of plots

Dharman
  • 30,962
  • 25
  • 85
  • 135
Marshall K
  • 302
  • 1
  • 8