Home > Back-end >  How to properly set margins in a base R figure with multiple plots
How to properly set margins in a base R figure with multiple plots

Time:07-15

I consulted multiple tutorials, YouTube videos, StackOverflow threads, but couldn't figure out what to do to properly visualize 9 plots in the same image, without squeezing/resizing them.

Here is my code, can anyone help visualizing them appropriately?

layout(matrix(c(1,2,3,4,5,6,7,8,9,0), 5, 2, byrow = TRUE))

par(mar=c(0,0,0,0))

for(k in 1:9){
  dat <- rnorm(200)
  hist(dat, prob = T,
       main = substitute(paste("Empirical distribution of"),
                     list(h=c(1:9)[k])),
       xlab = substitute(beta[h],
                     list(h=c(1:9)[k])))

  lines(density(dat),lwd = 2)
}

As you can see from the image below, the result looks quite messy!

enter image description here

Edited:

If I increase the margins with, for example:

par(mar=c(4, 2, 1.5, 0.5))

The xlab and ylab are displayed correctly, but it looks like the histograms get "squeezed" to fit inside the remaining available space... Is there any option I could use to preserve the original size of the histograms? I don't understand what am I missing here...

enter image description here

CodePudding user response:

Looks like you don't fully understand what mar means. It refers to the number of text lines reserved on "bottom", "left", "top" and "right" for each subplot (that is, clockwise order from "bottom").

I usually find par(mar=c(2, 2, 1.5, 0.5)) comfortable, which gives a compact display without showing xlab and ylab. But if you want to see xlab and ylab, you need to increase margin and use par(mar=c(4, 4, 1.5, 0.5)).

Below is the figure used for R's official manual:

mar

  • Related