How to decompress a large Grid? - r

I created a super large grid and now I cannot view the image.
Is there a way for me to save it as png or similar and use a magnifying glass to see each facet?
I have tried viewing it in the R itself, saving with ggsave, saving with cairo and exporting.
Here, I show you my script and the image
#install.packages("ggh4x")
library(ggh4x)
qPCR_data$Treatment <- factor(qPCR_data$Treatment, levels =c("NW","S","NS","Ec6","Ec7"))
qPCR_data$Wing <- factor(qPCR_data$Wing, levels =c("Wounded","Control"))
qPCR_grid <- ggplot(qPCR_data, aes(x=factor(SampleID), y=CtGene, colour=Replicate,group=Gene)) +
geom_point(aes(fill=Gene),position=position_dodge(0.3))+
facet_nested(TimePoint~Wing+Treatment)
ggsave("qPCR_grid2.png", plot=qPCR_grid)
qPCR_grid

Related

R: Using magick to display 4 png images in 1 panel

I have many images (plots) saved as png from another script:
x1.png
x2.png
x3.png
x4.png
y1.png
y2.png
etc. I am trying to make a gif of these, which I have done successfully in magick. However, this loops through 1 image per frame. I am trying to load 4 images at a time, and stitch them together on a panel, and create a gif of these panels.
I have successfully created a gif of these images.
However, I want to load 4 images at a time, and then form these into a gif.
y <- (list.files(path='foo/bar/', pattern = '*1.png', full.names = TRUE))
plot(y[1]) # does nothing
How can I load or display 4 pngs at a time in one panel?
I can do this usually by using:
par(mfrow=c(2,2))
plot(a)
plot(b)
plot(c)
plot(d)
however I am using magick to load pngs (of plots, but I obviously can't treat them as regular plots)
img1 <- magick::image_read("foo/bar/x1.png")
plot(img1) # does nothing
print(img1) # displays img 1 as a plot, and prints some details in the output window.
I'm sure I could rewrite my other code to display 4 plots, and save them as 1 png, but I am trying to write a small separate script to load these pre-existing images, and stitch the pngs together. Is this possible using par(mfrow=c(2,2))?
I'm sure I'm missing a great many simple things. Thank you all for your time.
You can do that in ImageMagick using montage. For example
montage lena.jpg mandril3.jpg zelda1.jpg peppers.jpg -tile 2x2 -geometry +0+0 montage.gif
To run ImageMagick commands (or any terminal code) in R, you just have to enclose it in quotes and pass that to the function system().
system("montage lena.jpg mandril3.jpg zelda1.jpg peppers.jpg -tile 2x2 -geometry +0+0 montage.gif")

Reading PDF plots, arranging them on a grid, save in one-page PDF using R

I have 3 R plots saved as pdf files (upper_left.pdf, upper_right.pdf, lower.pdf) as vector graphic and want to make a one-page pdf file and arrange them on it as follows:
What I have tried already
I have tried reading the pdf's using magick::image_read_pdf and appending them using magick::image_append. More specifically,
library(magick)
panel.ul <- image_read_pdf("upper_left.pdf")
panel.ur <- image_read_pdf("upper_right.pdf")
panel.l <- image_read_pdf("lower.pdf")
whole <- c(panel.ul, panel.ur) %>%
image_append() %>%
c(panel.l) %>%
image_append(stack = TRUE)
The first issue is magick::image_read_pdf imports the plot as png (if I'm right, not vector graphic though).
magick::image_append also 'works' and gives me what I want in viewer pane (in RStudio, next to Help).
I then try to save them using export::graph2pdf(whole), but it gives me a blank page.
So, if I am to use magick, there are two issues that need to be solved:
importing plots as vector graphic objects (do not know the technical term in R)
Exporting the stacked plot to a vector pdf file.
How can I solve it? thanks in advance.
You're basically done. You only need to add
plot(whole) # plot the external object generated in ImageMagick to R's plotting device
savePlot(type = "pdf") # saves the current plotting device to a pdf file.
You will find your plot in your workoing directory called "Rplot.pdf".
savePlot has many options to customize your pdf output. Make sure to check ?savePlot.
To recreate your scheme from above youll need to temporarily save the upper panel as a separate pdf before you paste it to on top of the lower panel:
whole2 <- image_append(c(panel.ul, panel.ur))
plot(whole2)
savePlot("whole2.pdf", type = "pdf")
If the upper and lower panel do not look proportionate you can use the heght and width parameters of savePlot to adjust the size of the first pdf.
panel.upr <- image_read_pdf("whole2.pdf")
final <- image_append(c(image_append(panel.upr),panel.l), stack = TRUE)
plot(final)
savePlot("final.pdf", type = "pdf")

What is a simple way to thumbnail some plots in R Markdown/knitr?

I am using R Markdown with knitr in R Studio to create and update a simple project website to keep my colleagues up to speed with a data analysis model I am building. There are some plots on the page, which (for smaller plots) so far has worked nicely, they can see the code and the results in the same place.
However, some plots have grown very large (and must remain large to allow quick side-by-side comparison of models), and don't fit on the page very well. I've used separately uploaded pdfs (with a link on the page) for some of them. It would be nicer if there was a simple way of generating thumbnails of some of these plots, so that the user can view a small plot image, click on it and then inspect the much larger image in detail. However, if it takes a lot of manual scripting for each plot instance, I'd rather not waste time on it and just upload the couple of pdfs. A similar question here talks about package, knitrbootsrap, but I don't want to thumbnail all my plots, just a select few. The package seems to use Magnific popup, but integrating it myself in a Markdown page seems like a hassle(?). I didn't find anything in the R Markdown reference guide. Of course a one way would be to generate two plots, one tiny, which is shown, and link it to another, larger plot image/pdf that is uploaded separately - but a simpler, more automatic way would be desireable.
Hence the question - is there a simpler way to generate clickable plot thumbnails in R Markdown?
So, this is what I came up with. Add a plot hook, so that you generate a full-resolution pdf image before generating a small image in the chunk:
allow_thumbnails <- function(x, options) {
if (!is.null(options$thumb)) {
filename <- sprintf("%s.full.pdf", strsplit(basename(x), "\\.")[[1]][1])
absolute_path <- file.path(dirname(x), filename)
# generate the full resolution pdf
pdf(absolute_path, width = options$thumb$width, height = options$thumb$height)
eval(parse(text = options$code))
dev.off()
# add an html link to the low resolution png
options$fig.link = absolute_path
}
knitr:::hook_plot_md_base(x, options)
}
And then in the Rmd file, I define the size of the full-resolution image using the thumb argument:
```{r init}
knit_hooks$set(plot = allow_thumbnails)
```
```{r my_large_plot, fig.width = 15, fig.height = 15, thumb = list(width = 45, height = 45)}
my_large_plot()
```
This generates an html file with a clickable png that takes you to the pdf.

R: Bitmap output in PDF

A lot of the time, I find it very useful to output graphics with pdf() as it allows me to scroll through pages and observe subtle differences (e.g. the page numbers may correspond to a particular parameter in a simulation).
Sometimes if the plot is quite packed with information, the fact that the PDF is a vector graphic means that it takes a long time to load in a PDF reader and is useless for scrolling through pages. I could plot with png(), but this would result in many image files.
My ideal solution would be to have a device that will plot a bitmap graphic (e.g. PNG) to a PDF.
I have read that cairo_pdf() outputs to a bitmap sometimes? Or I could write something that outputs to PNG, then combines these all together into a PDF?
Any other thoughts? Or does anyone have a solution for this already?
UPDATE: have now added method based on readPNG() as suggested in comments above. It's a bit slower (3s vs 9s) and seems to result in slightly larger file sizes than ImageMagick. rasterImage() interpolation makes no difference to filesize or timing, but alters the appearance slightly. If it's FALSE, then it looks the same as ImageMagick
I have just come up with the following solution using ImageMagick. It's not perfect, but it seems to work well so far.
png2pdf <- function(name=NULL,removepngs=TRUE,method="imagemagick",pnginterpolate=FALSE){
# Run the png() function with a filename of the form name%03d.png
# Then the actual plotting functions, e.g. plot(), lines() etc.
# Then dev.off()
# Then run png2pdf() and specify the name= argument if other pngs exist in the directory
# Need to incorporate a way of dealing with non-square plots
if(is.null(name)){
names <- list.files(pattern="[.]png")
name <- unique(sub("[0-9][0-9][0-9][.]png","",names))
if(length(name)!=1) stop("png2pdf() error: Check filenames")
}else{
names <- list.files(pattern=paste0(name,"[0-9][0-9][0-9][.]png"))
}
# Can change this to "convert" if it is correctly in the system path
if(method=="imagemagick"){
cmd <- c('C:\\Program Files\\ImageMagick-6.9.0-Q16\\convert.exe',names,paste0(name,".pdf"))
system2(cmd[1],cmd[-1])
}else if(method=="readPNG"){
library(png)
pdf(paste0(name,".pdf"))
par(mar=rep(0,4))
for(i in 1:length(names)){
plot(c(0,1),c(0,1),type="n")
rasterImage(readPNG(names[i]),0,0,1,1,interpolate=pnginterpolate)
}
dev.off()
}
if(removepngs) file.remove(names)
}

Plotting images but holding visualization until instruction in R

I want to load two jpeg images in R consecutively but they are quite large (4000X3000 pixels)
So simply doing
library(biOps)
x <- readJpeg("image.jpg")
plot(x)
Takes a while. When the first image is displayed the user would have to fill in some observations on the image. I wanted to know if it was possible to plot the image but pause the actual visualization so as to take advantage of the time the user is filling in the data I mentioned only to display the image later, maybe upon an instruction of the user like pressing the enter key.
Can this be done?
One option is to use animation package. saveHTML will create a html file animated by SciAnimator library. You can show the first plot and stop the visualisation, go to the next, use a timer,...
ll.imgs <- list.files(Imgs_folder,patt='jpg',full=TRUE)
saveHTML({
for(i in seq_along(ll.imgs)){
x <- readJpeg("image.jpg")
plot(x) ##maybe you should try grid.raster(x) from grid package
}
}, img.name = "plots", imgdir = "plots_dir",
htmlfile = "random.html", autobrowse = FALSE,
title = "Plotting images but holding visualization until instruction",
outdir=getwd())

Resources