I am trying to create a scatter plot matrix following the cookbook recipe found at https://r-graphics.org/recipe-scatter-splom. However, 3 of the 4 histograms are cut off either on the left, right, or both sides of the x-axis. How do I prevent this from happening? Code below:
dftest <- structure(list(eOver = c(29, 14, 12, 11, 9, 47, 29, 12, 24, 30, 23, 20),
eUnder = c(31, 43, 67, 66, 61, 83, 56, 67, 69, 63, 55, 69),
nHerb = c(8, 31, 7, 9, 2, 3, 2, 21, 11, 3, 6, 15),
nUnder = c(3, 0, 2, 0, 0, 4, 2, 2, 3, 4, 1, 1)),
row.names = c(NA, 12L),
class = "data.frame")
panel.cor <- function(x, y, digits = 2, prefix = "", cex.cor, ...) {
usr <- par("usr")
on.exit(par(usr))
par(usr = c(0, 1, 0, 1))
r <- abs(cor(x, y, use = "complete.obs"))
txt <- format(c(r, 0.123456789), digits = digits)[1]
txt <- paste(prefix, txt, sep = "")
if (missing(cex.cor)) cex.cor <- 0.8/strwidth(txt)
text(0.5, 0.5, txt, cex = cex.cor * (1 + r) / 2)
}
panel.hist <- function(x, ...) {
usr <- par("usr")
on.exit(par(usr))
par(usr = c(usr[1:2], 0, 1.5) )
h <- hist(x, plot = FALSE)
breaks <- h$breaks
nB <- length(breaks)
y <- h$counts
y <- y/max(y)
rect(breaks[-nB], 0, breaks[-1], y, col = "white", ...)
}
panel.lm <- function (x, y, col = par("col"), bg = NA, pch = par("pch"),
cex = 1, col.smooth = "black", ...) {
points(x, y, pch = pch, col = col, bg = bg, cex = cex)
abline(stats::lm(y ~ x), col = col.smooth, ...)
}
pairs(dftest,
upper.panel = panel.cor,
diag.panel = panel.hist,
lower.panel = panel.lm
)