Save downloaded images in one PDF in R - r

I'm downloading a few .pngs of a website, saving them in a separate folder and now I'm trying to join them in a single pdf, each image on a different page.
Everything I've found uses a different language but I would love to do everything using R, is it possible?

This should do the trick:
#-- Load libraries
library(png)
library(grid)
#-- Parameters
nFiles <- 2
file_name <- "test"
#-- Open pdf
pdf(file = "test.pdf")
#-- Read the files & plot
for (i in 1:nFiles)
{
img <- readPNG(paste(file_name, i, ".png", sep = ""))
grid.raster(img)
if (i < nFiles) plot.new()
}
#-- Close pdf
dev.off()

Related

Problem with getting an image of a graph made in ggplot2 [duplicate]

In R, I use function savePlot to save graphs into image files. But my colleague can only open .jpgs and .gifs (probably because he's on vacation, reading emails on his mobile phone). I hate to create jpegs because especially the boxplots looks very ugly (whiskers blurred etc.). But the savePlot function only supports the following types:
type = c("wmf", "emf", "png", "jpg", "jpeg", "bmp",
"tif", "tiff", "ps", "eps", "pdf")
How can I save plot in GIF in R?
EDIT: if possible, ideal solution should work without installing ImageMagick (so that the R script is easily portable).
R doesn't have a native GIF graphics driver, mostly (completely?) due to the patent-encumbrances of the GIF format: see http://tolstoy.newcastle.edu.au/R/help/05/02/12809.html .
There is a function in the caTools package (write.gif()) but it is specifically designed for writing images. If you wanted to use it you have to do something hacky to convert your plot to an image first (e.g. save as PNG and then read it back into R as an image). For example:
png("myPlot.png")
plot(rnorm(1000),rnorm(1000))
dev.off()
library(png)
P1 <- readPNG("myPlot.png")
library(caTools)
write.gif(P1,"myPlot.gif")
showGIF <- function(fn) system(paste("display",fn))
showGIF("myPlot.gif")
unlink("myPlot.gif") ## clean up
?write.gif() has a lot of stuff about color indexing that I didn't read but that might be important for more complex graphs ...
The animation package has a saveGIF() function to save GIFs, but (1) it is designed for saving multi-frame animations (not general graphics), and (2) it does it by calling ImageMagick.
It's easier just to construct that function yourself.
install ImageMagick (http://imagemagick.org)
save as a PNG, then use ImageMagick to convert.
For example:
png("myPlot.png")
plot(rnorm(1000),rnorm(1000))
dev.off()
system("convert myPlot.png myPlot.gif")
unlink("myPlot.png") ## clean up
showGIF("myPlot.gif")
unlink("myPlot.gif") ## clean up
Of course you can either of these in a function if you want to use them regularly.
UPDATE: I spent a while longer on this, to try to get a pure-R solution, but don't yet have a working solution. Suggestions or edits welcome ...
## needs ImageMagick: just for testing ...
showGIF <- function(fn) system(paste("display",fn))
The main function:
saveGIF <- function(fn,verbose=FALSE,debug=FALSE) {
require(png)
require(caTools)
tmpfn <- tempfile()
on.exit(unlink(tmpfn))
savePlot(tmpfn,type="png")
P1 <- readPNG(tmpfn)
dd <- dim(P1)
P1 <- aperm(P1,c(3,1,2),resize=TRUE) ## P1[,1,15]
dim(P1) <- c(dd[3],prod(dd[1:2]))
P1 <- t(P1)
if (verbose) cat("finding unique colours ...\n")
P1u <- unique(P1)
rgbMat <- function(x) {
rgb(x[,1],x[,2],x[,3])
}
if (verbose) cat("creating colour index ...\n")
pp <- paste(P1[,1],P1[,2],P1[,3],sep=".")
## make sure factor is correctly ordered
ind <- as.numeric(factor(pp,levels=unique(pp)))
if (verbose) cat("finding colour palette ...\n")
if (nrow(P1u)>256) {
if (verbose) cat("kmeans clustering ...\n")
kk <- kmeans(P1u,centers=256)
ind <- kk$cluster[ind]
pal <- rgbMat(kk$centers)
} else {
pal <- rgbMat(P1u)
}
## test:
if (debug) {
dev.new()
par(mar=rep(0,4))
image(t(matrix(ind-1,nrow=dd[1])),col=pal,axes=FALSE,ann=FALSE)
}
if (verbose) cat("writing GIF ...\n")
indmat <- matrix(ind-1,nrow=dd[1])
storage.mode(indmat) <- "integer"
write.gif(indmat,fn,col=as.list(pal),scale="never")
}
X11.options(antialias="none")
image(matrix(1:64,nrow=8),col=rainbow(10))
saveGIF("tmp.gif",verbose=TRUE,debug=TRUE)
showGIF("tmp.gif")

Plotting multiple .TIFF images together with individual titles in R

I would like to plot multiple .TIFF images in R and add individual titles to them. Without the titles, this piece of code gets the job done:
require(raster)
setwd("...")
files = list.files(pattern="*.tif")
tiff("balanded_1.tiff", units="in", width=21, height=26, res=300, compression = 'lzw') #for saving
par(mfrow=c(5,3))
for (i in 1:15) {
plotRGB(brick(files[i]))
}
dev.off() #save figure
However, if I try to add individual titles to the images using 'plotRGB()', it automatically adds axes to them (because 'axes=TRUE' becomes a requirement in the 'plotRGB()' function), and I get something like this:
plotRGB(brick(files[2]), axes=TRUE, main="TITLE", xlab="", ylab="")
I understand that 'plotRGB()' is probably not the right function for the job (since I am not plotting maps), but I wonder if there is a way to make it work? If not, is there an alternative I could use? Thank you in advance.
I managed to find a solution to this problem using a more appropriate package for image manipulation:
require(magick)
setwd("...")
files = list.files(pattern="*.tif")
tiff("balanded_1.tiff", units="in", width=21, height=26, res=300, compression = 'lzw')
par(mfrow=c(5,3))
for (i in 1:15) {
name <- files[i]
lag <- strsplit(name, "_")[[1]][2] #get the name right for the image
match <- strsplit(name, "_")[[1]][4]
lead <- strsplit(name, "_")[[1]][6]
lead <- strsplit(lead, ".tiff")[[1]][1]
name <- paste(" Lag=",lag,", Match=1:",match,", Lead=",lead, sep = "") #put the name together
img <- image_annotate(image_read(files[i]), name, font = 'Times', size = 120) #read the image and add the name
img <- image_crop(img, "1500x1050")
plot(img)
}
dev.off() #save figure

Faster way to save plotly plot as a pdf file (instead of orca)

I have a few plotly plots that I need to save as pdf/eps files to add to a LaTex report. Currently I'm using orca to achieve this but it is quite slow, is there another, faster way to do this?
library(plotly)
library(orca)
pname <- plot_ly(...) # plotly plot object
fname <- 'sample_file' # file name to save plot as
orca(p = pname, file = fname, format = 'pdf', width = 1600, height = 1000)

R: How to save plot of "find_droughts" function from "lfstat" package as an image using code?

When I try to save this particular plot as an image, I only get an empty white image file. With this same code I managed to save multiple other "normal" plots, but it just won't work for find_droughts function (maybe also for some others).
I can save the plot manually by clicking "Export" in the Viewer, but I have a lot of plots to save and I would really like to do it using code.
This code generates the plot I have in mind:
library(lfstat)
# random data
date<-seq(from=as.Date("2018-01-01"), to=as.Date("2018-12-31"), by="days")
flow<-c(runif(150, min=50, max=180),runif(95, min=25, max=50),runif(120, min=50, max=400))
# dataframe
flow.df<-data.frame(day(date),month(date),year(date),flow)
names(flow.df)<-c("day", "month", "year", "flow")
#dataframe to lfobj
lfobj <- createlfobj(flow.df,hyearstart = 1, baseflow = FALSE)
# lfobj to xts
flowunit(lfobj)<-"m^3/s"
xts<-as.xts(lfobj)
# find droughts
droughts<-find_droughts(xts, threshold=47, drop_minor = 0)
# Save plot as .png
savehere<-"C:/.../"
filename<-"myplot.png"
mypath <- file.path(paste(savehere,filename, sep = ""))
png(file=mypath)
plot(droughts)
dev.off()
I need help with the last step - "# Save plot as .png".
And if anybody knows a way to change title of this plot, names of axis labels and so on, this would also help.
I think the reason is that the default plot from the 'find_droughts' function is an interactive plot based on dygraph package.
I can think of two ways to overcome your issue.
If you want to plot static png, you can define on the plot function the type of the plot, so it's not the default (interactive) anymore. Based on your code, it will be:
# Save plot as .png
savehere <- "C:/.../"
filename <- "myplot.png"
mypath <- file.path(paste(savehere,filename, sep = ""))
png(file=mypath)
plot(droughts, type='l') # by defining type 'l', it will provide a plot of xts object, which is static
dev.off()
If you want to plot an interactive plot, you can do something as below:
# Save plot as .html
library(htmlwidgets) # for saving html files
savehere <- "C:/.../"
filename <- "myplot.html"
mypath <- file.path(paste(savehere,filename, sep = ""))
InteractivePlot <- plot(droughts)
saveWidget(InteractivePlot , file=mypath)
# the above function will generate the interactive plot as an html file, but also a folder, which you might want to delete, since it's not required for viewing the plot. For deleting this folder you can do the following
foldername <- "myplot_files"
mypath <- file.path(paste(savehere,foldername , sep = ""))
unlink(mypath, recursive = T)
Hope this helps.

Unable to generate PDF with neural network graph

I'm trying to create a hard-copy image of a neural network graph and it keeps failing. If I try to create a PNG, nothing is generated, and if I try to generate a PDF I get a small file output that refuses to open with "file may be damaged" errors. If I just let it display in a graphics window, the image comes up fine.
I'm using 2.15.1 on OS X (10.7.4), built by Macports. The code I'm working with at the moment:
library(ALL)
library(neuralnet)
data(ALL)
ALL.pdat <- pData(ALL)
bt <- factor(substring(ALL.pdat$BT,1,1))
all.sds <- apply(exprs(ALL),1,sd)
top.10.sds <- rank(all.sds)>length(all.sds)-10
exprs.top.10 <- as.data.frame(t(exprs(ALL)[top.10.sds,]))
nn.data <- cbind(exprs.top.10, as.numeric(bt))
## Gene names start with a number, and that causes problems when trying to set up the
## formula for neuralnet.
col.names <- paste("g", colnames(nn.data), sep = '')
col.names[11] <- "bt"
colnames(nn.data) <- col.names
my.nn <- neuralnet(bt ~ g36108_at + g36638_at + g37006_at + g38096_f_at + g38319_at + g38355_at + g38514_at + g38585_at + g39318_at + g41214_at, nn.data, hidden = 10, threshold = 0.01)
summary(my.nn)
pdf("./nn-all.pdf")
plot.nn(my.nn)
dev.off()
png("./nn-all.png")
plot.nn(my.nn)
dev.off()
I've even rebooted the machine to make sure that all the memory is cleared up, and that didn't help any.
Simple reproducible example:
pdf("test.pdf")
set.seed(42)
plot(runif(20),rnorm(20))
png("test.png")
set.seed(42)
plot(runif(20),rnorm(20))
dev.off()
If I try to open the PDF with Adobe Reader on my German Windows 7, I get a nice informative error message telling me that the file cannot be opened because the file is in use by another application. This can be fixed easily:
pdf("test.pdf")
set.seed(42)
plot(runif(20),rnorm(20))
dev.off() #make sure to close the graphics device
png("test.png")
set.seed(42)
plot(runif(20),rnorm(20))
dev.off()
Edit:
The problem is plot.nn. Until the package gets patched, you need to redefine plot.nn manually as shown in this answer.

Resources