KevCaz's Website

I do love create figures with R, I found quite satisfying to make them very personalized, yet reproducible! However I sometime wish that combining two plots was easier (as it often requires to build larges matrices and crazy layout() calls). I was looking for a simple way to do basic combinations of customized R figures, and I stumbled on this discussion on showing how easy it is to do so with ImageMagick. Let me exemplify with a reproducible example based on two silhouettes by Timothey Bartley available on PhyloPic (note that I use 2 images here, but it works the same way with more):

  1. lake trout (Salvelinus namaycush);
  2. yellow perch (Perca flavescens).

Let’s first create a folder assets and download the silhouettes with wget:

mkdir assets
wget -O assets/salvelinus_namaycush.png
wget -O assets/perca_flavescens.png

Here there are:

  1. perca_flavescens.png
  1. salvelinus_namaycush.png

To combine them, you just need to use convert with the option +append to combine them horizontally or -append to combine them vertically. Let’s start with +append:

convert +append assets/perca_flavescens.png assets/salvelinus_namaycush.png assets/fishH.png

💥 Neat, right? There is something about the default behavior you need to know, though. Indeed, by default, the images are top-aligned and so, if one image is shorter, a patch is added to make the image of the same size and this patch has a white background by default. You may not have noticed this here, but it’d be obvious with a black background:

convert +append -background black assets/perca_flavescens.png assets/salvelinus_namaycush.png assets/fishH1.png

By showing you this problem, I’ve almost solved it! So if you want to get rid of the white background, add a transparent one!

convert +append -background transparent assets/perca_flavescens.png assets/salvelinus_namaycush.png assets/fishH2.png

And now let’s combine the image vertically with a transparent background for the patch:

convert -append -background transparent assets/perca_flavescens.png assets/salvelinus_namaycush.png assets/fishV.png

Love this trick! Two short remarks to end this note:

  1. there are many programming langages that interface ImageMagick;
  2. the R 📦 patchwork is making this kind of operation really easy with ggplot2.

See ya next note ✏