canerb
canerb

Reputation: 23

R - add title to images with rasterImage

I have 12 twelve PNG files which I want to combine in a single plot with 4x3 grid in R.

So far I can create the grid with,

plot(c(0,4), c(0,3), type = "n", xaxt = "n", yaxt = "n", xlab = "", ylab = "")

and I can add images to it with,

rasterImage(readPNG("image1.png"), 0, 3, 1, 2)
rasterImage(readPNG("image2.png"), 1, 3, 2, 2)

etc.

I get what I want, but I also want to add a title to each image in the plot. Like image1 should have a. Image1 and image2 should have b. Image2 on top of the images. Is there a way to do in R?

Thanks in advance.

Upvotes: 2

Views: 5066

Answers (2)

jbaums
jbaums

Reputation: 27388

@BondedDust's suggestion to use text is perfect, but using the mfrow (or mfcol) graphic parameter in par to layout the grid of plots might be sensible. You can then use plot(..., main='foo') or title(main='foo') to add the titles. For example:

  1. Download some example png graphics, and read them into a list:

    library(png)
    pngs <- lapply(LETTERS[1:12], function(x) {
      u <- 'http://icons.iconarchive.com/icons/mattahan/umicons/64'
      download.file(mode='wb', sprintf('%s/Letter-%s-icon.png', u, x), 
                    f <- tempfile(fileext='.png'))
      readPNG(f)
    })
    
  2. Use mfrow to set the plot to have 4 rows and 3 columns, and add an upper margin for titles with mar. Then use sapply (for example) to iterate over elements of pngs (well, actually the indexes, 1 through 12, of the elements), plotting each in turn:

    par(mfrow=c(4, 3), mar=c(0, 0, 3, 0))
    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)
    })
    

enter image description here

Upvotes: 3

IRTFM
IRTFM

Reputation: 263352

Try this:

 text(x=0.5,y=2.95, labels="a. Image1")
 text(x=1.5,y=2.95, labels="b. Image1")

If it needed to be bold, then plotmath expressions are needed:

text(x=1.5,y=2.95, labels=expression( bold(b.~Image1) )  )

Upvotes: 1

Related Questions