views:

78

answers:

3

I need to plot and display several jpeg images in a single combined display (or canvas?). For example, suppose I have images {a,b,c,d}.jpg, each of different size, and I would like to plot them on one page in a 2x2 grid. It would be also nice to be able to set a title for each subplot.

I've been thoroughly looking for a solution, but couldn't find out how to do it, so any ideas would really help. I would preferably use a solution that is based on the EBImage package.

+2  A: 

There are two ways how to arrange several plots with base graph functions, namely par(mfrow=c(rows,columns)) (substitute rows and columns with integers) and layout(mat) where mat is a matrix like matrix(c(1,2,3,4)).
For further info see ?par, ?layout, and especially Quick-R: Combining Plots.

However, as your question is about images I don't know if it helps you at all. If not, I am sorry for misinterpreting your question.

Henrik
+1  A: 

To add to Henriks solution, a rather convenient way of using the par() function is:

jpeg(filename="somefile.jpg")
op <- par(mfrow=c(2,2)
#plot the plots you want
par(op)
dev.off()

This way, you put the parameters back to the old state after you ran the code. Be aware of the fact this is NOT true if one of the plots gave an error.

Be aware of the fact that R always put the plots in the same order. Using mfrow fills the grid row by row. If you use mfcol instead of mfrow in the code, you fill up column by column.

Layout is a whole different story. Here you can define in which order the plots have to be placed. So layout(matrix(1:4,nrow=2) does the same as par(mfcol=c(2,2)). But layout(matrix(c(1,4,3,2),ncol=2)) places the first plot lefttop, the next one rightbottom, the third one righttop, and the last one leftbottom.

Every plot is completely independent, so the titles you specify using the option main are printed as well. If you want to have more flexibility, you should take a look at lattice plots.

Joris Meys
+1  A: 

If you do not want the images in a regular grid (the different sizes could imply this), then you might consider using the subplot function from the TeachingDemos package. The last example in the help page shows using an image as a plotting character, just modify to use your different images and sizes/locations.

The ms.image function (same package) used with my.symbols is another possibility.

Greg Snow