How to combine multiple image files into one image file using R

If you create plots using ggplot and want to merge them into one plot, it is simple to do using the cowplot package. However, it might get trickier if you’re going to combine your saved image files or plots into one image file. In this post, I will show you how to use R libraries magick and cowplot to merge image files.

To combine saved image files, you need first to use the draw_image() function of the cowplot package to place an image somewhere onto the drawing canvas. This function requires the magick package to read the image. Using this function, you can set height, width, location, horizontal and vertical justification, and other parameters for your input images.

Once you have all the images in local variables, you can use the plot_grid() function of the cowplot package to merge them into a grid, i.e., one image file. The number of rows and columns in the grid can be set by the parameters nrow and ncol, respectively. Using the labels parameter, you can also assign labels to each image file in the combined file.

In the following R code, I combine four fruits’ jpeg files into a 2×2 grid with “auto” labels. The final merged image file is a png file. Please let me know whether or not the code works for you. You need to replace the image files in the code with your image files.

#### Combine image files
library(magick)
library(cowplot)
f1 <- ggdraw() + draw_image("f1.jpeg")
f2 <- ggdraw() + draw_image("f2.jpeg")
f3 <- ggdraw() + draw_image("f3.jpeg")
f4 <- ggdraw() + draw_image("f4.jpeg")

png(filename = "combined_fruits.png", width = 6, height = 6, units = "in", res = 300)
plot_grid(f1, f2, f3, f4, labels = "auto", ncol = 2, label_size=10)
dev.off()

Similar Posts

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.