I have a list of images that I would like to combine into one image per group. Each image has a name and what type of chart it is. I'm hoping there is a way to use the name to group the images and return an output of a single jpg or png for each group. the combined image would look like the following:
The folder has a list of images with the following naming structure: In this case, I would like to have 3 output combined pngs based on bart, lisa and marge.
"bart Cum Oil.jpg"
"bart GOR.jpg"
"bart Legend.jpg"
"bart Oil Rate.jpg"
"lisa Cum Oil.jpg"
"lisa GOR.jpg"
"lisa Legend.jpg"
"lisa Oil Rate.jpg"
"marge Cum Oil.jpg"
"marge GOR.jpg"
"marge Legend.jpg"
"marge Oil Rate.jpg"
Below is a sample of four images that i would combine since all images have "bart" in the name.
One option is to use magick::image_montage
. The only trick is to create a 2x2 grid and insert a blank image as the 3rd object.
library(magick)
#> Linking to ImageMagick 6.9.12.3
#> Enabled features: cairo, freetype, fftw, ghostscript, heic, lcms, pango, raw, rsvg, webp
#> Disabled features: fontconfig, x11
imgs_url <- c('https://i.sstatic.net/TqnwC.png',
'https://i.sstatic.net/qIDXh.png',
'https://i.sstatic.net/B36ko.png')
imgs <- image_read(imgs_url)
imgs <- c(imgs[1:2], image_blank(width = 3, height = 5), imgs[3])
image_montage(imgs, tile = '2x2', geometry = "x200+3+5")
Created on 2021-07-13 by the reprex package (v2.0.0)
If you want to group the images by name, one way is to capture the above workflow in a function, and add a grepl
statement to identify which subset of images to plot.
I don't have all of the images, so this is untested. But it would look something like this.
my_files <- c("bart Cum Oil.jpg",
"bart GOR.jpg",
"bart Legend.jpg",
"bart Oil Rate.jpg",
"lisa Cum Oil.jpg",
"lisa GOR.jpg",
"lisa Legend.jpg",
"lisa Oil Rate.jpg",
"marge Cum Oil.jpg",
"marge GOR.jpg",
"marge Legend.jpg",
"marge Oil Rate.jpg")
# remove oil rate image paths
my_files <- my_files[!grepl('Oil Rate', my_files)]
# create function
make_grid <- function(group, path_to_files){
f <- files[grepl(group, files)]
imgs <- image_read(f)
imgs <- c(imgs[1:2], image_blank(width = 3, height = 5), imgs[3])
image_montage(imgs, tile = '2x2', geometry = "x200+3+5")
}
# create lisa image grid
make_grid('lisa', my_files)
# create all image grids
lapply(c('bart', 'lisa', 'marge'), make_grid, path_to_files = my_files)