It is simple to print an image and save it on disk just:
fit <- lm(some ~ model)
png(filename=\"your/file/location/name.png\")
plot(fit)
dev.off()
Just to add an example about the xlsx package, as far as i can tell it requires you to first save the picture, then import it to the xlsx file, see a reproducible example of exporting to an existing book below:
# Setup
x <- c('tidyverse', 'rJava', 'xlsxjars', 'xlsx')
sapply(X=x, FUN = require, character.only = TRUE)
# Create graph---------
dcs <- ggplot(mtcars) +
geom_point(aes(cyl, disp))
# Export Pic -----------
pic_path <- "C:/home/dcs.jpeg"
png(filename = pic_path)
plot(dcs)
dev.off()
# Add to existing book -------------
xl_path <- "C:/home/a.xlsx"
wb <- loadWorkbook(xl_path)
ws <- getSheets(wb)["Summary"][[1]]
addPicture(file = pic_path, sheet = ws)
saveWorkbook(wb, xl_path)
# Kill pic
unlink(pic_path)
#Then write some data
write.xlsx(as.data.frame(output), xl_path, sheetName = 'data'))
I would use the xlsx
package. Check out the addPicture
function and the addDataFrame
function. I found this package fairly easy to work with.
You can do the same thing with the insertImage
function and using the openxlsx
package.
I've copied the example from above, but using the openxlsx package instead:
# Setup
x <- c('tidyverse', 'openxlsx')
sapply(X=x, FUN = require, character.only = TRUE)
# Create graph---------
dcs <- ggplot(mtcars) +
geom_point(aes(cyl, disp))
# Export Pic -----------
pic_path <- "C:/home/dcs.jpeg"
png(filename = pic_path)
plot(dcs)
dev.off()
# Add to a new work book -------------
wb <- openxlsx::createWorkbook()
addWorksheet(wb, "Plots")
insertImage(wb, "Plots", pic_path)
openxlsx::saveWorkbook(wb,
"~/example.xlsx")
# Kill pic
unlink(pic_path)