绘制多个光栅图像时填充白色 space

Fill up white space when Plotting Multiple Raster Images

如何在保持图像宽高比的同时最小化下图中的白色 space?

我指定了 mar=c(0,0,1,0) 页边距,但图像仍然 space 出来了。左侧、中间、底部和右侧有额外的间距。我希望图像以非常小的间距排列在网格中。

这是我目前的情况:

library(EBImage)
library(png)

pngs<-lapply(seq(1:4), function(x) {
   readPNG(system.file("images", "sample-color.png", package="EBImage"))
})

par(mfrow=c(2,2), mar=c(0, 0, 1, 0))
invisible(sapply(seq_along(pngs), function(i) {
  plot.new()
  plot.window(xlim=c(0, 1), ylim=c(0, 1), asp=1)
  rasterImage(pngs[[i]], 0, 0, 1, 1)
  title(paste0(letters[i], '. Image ', i), font.main=2)
}))

由于 asp=1,图像在您的示例中保持 512:768 的原始纵横比。相反,您的默认绘图设备的纵横比似乎接近 1:1。这不能很好地匹配并导致空白 spaces.

两种解法:

  1. 设置 asp=NA 以让图像通过扭曲图像来使用整个 space 设备。
  2. 通过设置 dev.new()widthheight 参数来调整绘图设备的大小。例如:

    library(EBImage)
    library(png)
    png <- readPNG(system.file("images", "sample-color.png", package="EBImage"))
    dev.new(width=4.5, height=8)
    par(mfrow=c(2,2), mar=c(0, 0, 1, 0))
    for(i in seq_len(4)){
        plot.new()
        plot.window(xlim=c(0, 1), ylim=c(0, 1), asp=1)
        rasterImage(png, 0, 0, 1, 1)
        title(paste0("Image ", i))
    }
    

如果 png 包的其他功能不是必需的,这里有另一个利用 EBImage 的解决方案。 EBImage 保持纵横比,除非图像被有意变换。

此解决方案需要更多工作来使用 text() 放置地块标签,但增加的成本可能会因具有更大的灵活性而被抵消。

# Starting from EBImage
  library(EBImage)
  fn <- system.file("images", "sample-color.png", package="EBImage")

# Single EBImage object with same four pictures
  pngs <- readImage(rep(fn, 4))

# Select spacing and margin for EBImage display/plot function
  spacing <- 50 # pixels between images
  margin <- 50 # pixels around edge
  nx <- 2 # number of rows for composite
  ny <- 2 # number of columns for composite
  dm <- dim(pngs)
  nframes <- dm[length(dm)]
  yadj <- -0.2 # offset for labels in y direction

# Indices, coordinates, and labels for text
  index <- seq_len(nframes)
  ix <- (index - 1)%%nx
  iy <- (index - 1)%/%nx
  xx <- ix*(dm[1] + spacing) + dm[1]/2
  yy <- iy*(dm[2] + spacing)
  labs <- sprintf("%s. Image %d", letters[index], index)

# Plot composite and add "titles" with text() function
  plot(pngs, all = TRUE, nx = nx, margin = margin, spacing = spacing)
  text(xx, yy, labs, adj = c(0.5, yadj))

# To eliminate ANY space in the composite make the following
# changes and re-run the code from "# Indices, coordinates..."
  spacing <- 0
  margin <- 0
  yadj <- 1.2
  dev.new(width = nx*dm[1]/200, height = ny*dm[2]/200) # 200 dpi image