Search code examples
rplotrastertiff

Plotting multiple .TIFF images together with individual titles in R


I would like to plot multiple .TIFF images in R and add individual titles to them. Without the titles, this piece of code gets the job done:

require(raster)

setwd("...")
files = list.files(pattern="*.tif")

tiff("balanded_1.tiff", units="in", width=21, height=26, res=300, compression = 'lzw') #for saving

par(mfrow=c(5,3)) 

for (i in 1:15) {
  plotRGB(brick(files[i]))
}

dev.off() #save figure

However, if I try to add individual titles to the images using 'plotRGB()', it automatically adds axes to them (because 'axes=TRUE' becomes a requirement in the 'plotRGB()' function), and I get something like this:

plotRGB(brick(files[2]), axes=TRUE, main="TITLE", xlab="", ylab="")

enter image description here

I understand that 'plotRGB()' is probably not the right function for the job (since I am not plotting maps), but I wonder if there is a way to make it work? If not, is there an alternative I could use? Thank you in advance.


Solution

  • I managed to find a solution to this problem using a more appropriate package for image manipulation:

    require(magick)
    
    setwd("...")
    files = list.files(pattern="*.tif")
    
    tiff("balanded_1.tiff", units="in", width=21, height=26, res=300, compression = 'lzw')
    par(mfrow=c(5,3)) 
    for (i in 1:15) {
      name <- files[i] 
      lag <- strsplit(name, "_")[[1]][2] #get the name right for the image
      match <- strsplit(name, "_")[[1]][4]
      lead <- strsplit(name, "_")[[1]][6]
      lead <- strsplit(lead, ".tiff")[[1]][1]
      name <- paste("   Lag=",lag,", Match=1:",match,", Lead=",lead, sep = "") #put the name together
      img <- image_annotate(image_read(files[i]), name, font = 'Times', size = 120) #read the image and add the name
      img <- image_crop(img, "1500x1050")
      plot(img) 
    }
    dev.off() #save figure