使用命令行时,无法通过openxlsx包将绘图插入XLSX

时间:2015-11-04 23:48:39

标签: r excel ggplot2 openxlsx

我正在尝试使用R中的openxlsx包将图插入XLSX文件中。 当我使用R GUI时,我能够完成此任务。

但是,使用批处理文件时,会创建绘图,但不会将其插入XLSX文件中。而是将其创建为与新创建的XLSX文件相邻的单独PDF文件(自动命名为“Rplots.pdf”)。数据框就可以很好地写入XLSX文件。

R脚本(名为“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)

批处理文件脚本:

"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

总之,我对如何使用RScript批处理文件完成此操作感到困惑。

有人有任何成功或可以指出我的错误吗?

2 个答案:

答案 0 :(得分:7)

我相信通过将图表输出到png设备然后利用insertImage包中的openxlsx,我找到了一种无缝完成此操作的方法。

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

希望这有助于任何可能面临同样问题的人。

答案 1 :(得分:0)

我是新来的,所以任何反馈都将受到赞赏:

对于那些使用Xvfb(虚拟X服务器环境)寻找Centos 7答案的人:

安装Xvfb

yum install xorg-x11-server-Xvfb

调用Rscript时,请使用xvfb-run -a在虚拟X服务器环境中运行脚本

xvfb-run -a Rscript /mnt/todd/examples/openxlsxChart.R

将x11()添加到实际的R文件中

library(openxlsx)
x11()
## Not run: 
## Create a new workbook
wb <- openxlsx::createWorkbook()

## Add a worksheet
openxlsx::addWorksheet(wb, "Sheet 1", gridLines = FALSE) 

## create plot objects
require(ggplot2)
p1 <- qplot(mpg, data=mtcars, geom="density",
            fill=as.factor(gear), alpha=I(.5), main="Distribution of Gas Mileage")
p2 <- qplot(age, circumference,
            data = Orange, geom = c("point", "line"), colour = Tree)

## Insert currently displayed plot to sheet 1, row 1, column 1
#print(p1) #plot needs to be showing
print(p1)
insertPlot(wb, 1, width = 5, height = 3.5, fileType = "png", units = "in")

## Insert plot 2
print(p2)
insertPlot(wb, 1, xy = c("J", 2), width = 16, height = 10,  fileType = "png", units = "cm")

## Save workbook
openxlsx::saveWorkbook(wb, "/home/tmamiya/insertPlotExample.xlsx", overwrite = TRUE)

## End(Not run)