I am having problems trying to automatically generate composite figures in R with different numbers of panels. When I have 3 or more panels in my figure, the margins are significantly different (smaller in the 1x3 plot), enough to cause R to plot labels incorrectly and detracting from the overall look.
# plot empty plot with box around plot and figure
plot_box <- function() {
plot(1, 1, type='n', bty='n', xaxt='n', yaxt='n', xlab='', ylab='')
box(lwd = 6)
box("figure", lwd=6, col='red')
}
png("box_test1.png", width=1000, height=500)
par(oma=c(0,0,0,0))
layout(t(1:2))
par(mar=c(3, 3, 3, 3))
plot_box()
par(mar=c(3, 3, 3, 3))
plot_box()
dev.off()
png("box_test2.png", width=1500, height=500)
par(oma=c(0,0,0,0))
layout(t(1:3))
par(mar=c(3, 3, 3, 3))
plot_box()
par(mar=c(3, 3, 3, 3))
plot_box()
par(mar=c(3, 3, 3, 3))
plot_box()
dev.off()
The images are scaled for display on stack overflow but as you can see from the device calls they are the exact same size.
This issue is very confusing to me and in all honestly feels like a bug, however I know the R plotting code is very mature so I'm hopeful for a solution.
You're setting margin using mar, which is in terms of lines, which is, well, difficult to manage properly.
‘mar’ A numerical vector of the form ‘c(bottom, left, top, right)’
which gives the number of lines of margin to be specified on
the four sides of the plot. The default is ‘c(5, 4, 4, 2) +
0.1’.
If you use mai instead, you will get a consistent physical size.
‘mai’ A numerical vector of the form ‘c(bottom, left, top, right)’
which gives the margin size specified in inches.
See also this bit of ?par:
The meaning of ‘character size’ is not well-defined: this is set
up for the device taking ‘pointsize’ into account but often not
the actual font family in use. Internally the corresponding pars
(‘cra’, ‘cin’, ‘cxy’ and ‘csi’) are used only to set the
inter-line spacing used to convert ‘mar’ and ‘oma’ to physical
margins. (The same inter-line spacing multiplied by ‘lheight’ is
used for multi-line strings in ‘text’ and ‘strheight’.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With