Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot insert plot into XLSX via openxlsx package when using command line

I'm trying to insert a plot into an XLSX file using the openxlsx package in R. When I use the R GUI, I am able to accomplish this.

However, when using a batch file, the plot is created but it is not inserted into the XLSX file. Instead, it is created as a separate PDF file adjacent to the newly created XLSX file (automatically named "Rplots.pdf"). The data frame is written into the XLSX file just fine.

The R script (named "insertPlot.R"):

library(ggplot2)
library(openxlsx)
wb <- createWorkbook()
addWorksheet(wb, "Data")
addWorksheet(wb, "Graph", gridLines=FALSE)
df <- data.frame(c(1:5), c(5:1))
names(df) <- c("x","y")
writeData(wb, "Data", df)
p <- ggplot(aes(x=x, y=y), data=df) + geom_line(size=1, colour="blue")
print(p)    #plot needs to be showing
insertPlot(wb, "Graph", width=11.18, height=7.82, fileType="png", units="in")
saveWorkbook(wb, "test.xlsx", overwrite=TRUE)

The batch file script:

"C:\Program Files\R\R-3.1.3\bin\RScript.exe" --no-save --no-environ --no-init-file --no-restore --no-Rconsole "C:\temp\insertPlot.R"

R GUI (Desired) Result

R Batch Command Result

In summary, I'm confused as to how to have an RScript batch file accomplish this.

Has anyone had any success or can point out my mistake?

like image 662
Jimmy G Avatar asked Nov 04 '15 23:11

Jimmy G


1 Answers

I believe I have found a way to seamlessly accomplish this by outputting the plot to a png device and then utilizing insertImage from the openxlsx package.

library(ggplot2)
library(openxlsx)

wb <- createWorkbook()
addWorksheet(wb, "Data")
addWorksheet(wb, "Graph", gridLines=FALSE)

df <- data.frame(c(1:5), c(5:1))
names(df) <- c("x","y")
writeData(wb, "Data", df)

png("graph.png", width=1024, height=768, units="px", res=144)  #output to png device
p <- ggplot(aes(x=x, y=y), data=df) + geom_line(size=1, colour="blue")
print(p)
dev.off()  #important to shut down the active png device
insertImage(wb, "Graph", "graph.png", width=11.18, height=7.82, units="in")

saveWorkbook(wb, "test.xlsx", overwrite=TRUE)

#unlink("graph.png")  #can optionally delete the original png file

Hope this helps anyone that could be facing the same issue.

like image 159
Jimmy G Avatar answered Nov 18 '22 16:11

Jimmy G