Site icon R-bloggers

Multiple plot in a single image using ImageMagick

[This article was first published on One R Tip A Day, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Sometimes you need to add several plots/images either by row or by column to a single page/sheet.
If you generate all your plot with R base graphics you can easily accomplished the task using the par() function, e.g., using par(mfrow=c(2,2)) and then drawing 4 plots of your choice.
However, if you need to create a single image build up from different sources, e.g. external images, plots not compatible with R base graphics, etc. , you can create/retrieve the single images and then merge them together using the tools from the Unix (Linux, Mac OS X, etc.) ImageMagick suite.

## Example # we generate some random plot require(seqLog) ## the first plot is taken from the seqLogo help ( ?seqLogo ) ## I selected this example on purpose because the seqLogo function is based on the grid graphics and is coded in such a way that doesn't allow the use of the par() function mFile <- system.file("Exfiles/pwm1", package="seqLogo") m <- read.table(mFile) pwm <- makePWM(m) png("seqLogo1.png", width=400, height=400) seqLogo(pwm) dev.off() ## totally unrelated png("plot1.png", width=400, height=400) plot(density(rnorm(1000))) dev.off()

Then you can type:

system("convert \\( seqLogo1.png plot1.png +append \\) \\( seqLogo1.png plot1.png +append \\) -background none -append final.png")

Remember that in R you have to start escape character with ‘\’ !

Or, alternatively, from the command line:

convert \( seqLogo1.png plot1.png +append \) \( seqLogo1.png plot1.png +append \) -background none -append final.png

See man convert and man ImageMagick for the full story.

To leave a comment for the author, please follow the link and comment on their blog: One R Tip A Day.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.