Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join images with data frames in r

This is probably a very basic question, but I am not familiar with images in R.

I want a PDF file with two joined imported images and a data frame as the image exemplifies:

Final output

This is the code that I am using but is not working.

library(grid)
library(useful)
library(magick)

# Read external images
imageA <- image_read("imageA.jpg") 
imageB <- image_read("imageB.jpg") 

# Create data frame
df <- data.frame(1:3)

# Create PDF
pdf("/Mydocument.pdf", width = 10, height = 20)
grid.newpage() 

# Create matrix layout
pushViewport(viewport(layout = grid.layout(1, 3)))

# Place elements inside grid
print(imageA, vp = vplayout(1, 1)) 
print(imageB, vp = vplayout(1, 2))
print(df, vp = vplayout(1, 3)) 

dev.off()
like image 634
Ushuaia81 Avatar asked Oct 17 '22 09:10

Ushuaia81


1 Answers

This code achieves what you want:

require('magick')

# Read external images
frink = image_read("https://jeroen.github.io/images/frink.png")
logo = image_read("https://www.r-project.org/logo/Rlogo.png")
imgs = c(frink, logo)

# concatenate them left-to-right (use 'stack=T' to do it top-to-bottom)
side_by_side = image_append(imgs, stack=F)

# save the pdf
image_write(side_by_side, path = "just_a_test.pdf", format = "pdf")

which gives this image:

enter image description here

You may want to scale the images vertically with image_scale(imgs, "x960") - changing 960 with whatever height you want, in pixels.

The vignette of magick explains this and much more: it is an incredibly valuable resource to work on images with R.


A note: if you are using R for the sole purpose of concatenating images, you are doing it wrong: use directly the convert img1.png img2.gif +append new_combined.pdf syntax of the convert commandline tool. It ships with the Image Magick library, the R magick package is a wrapper to it.

But if you have further treatments to do with R, then you can simply convert the image as a raster and continue working with it: as.raster(side_by_side)

like image 143
Jealie Avatar answered Oct 20 '22 10:10

Jealie