1

我正在尝试按照https://r-graphics.org/recipe-scatter-splom上的食谱创建散点图矩阵。但是,4 个直方图中的 3 个在 x 轴的左侧、右侧或两侧被截断。我该如何防止这种情况发生?下面的代码:

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
      )

问题情节

4

0 回答 0