Skip to content

insertImage inserts the image to all workbook sheets #555

@uwitt

Description

@uwitt

Hi,
Thanks for the great package!
I'm running R, version 4.3.3 under windows 11.
I need to run an R script in the terminal with Rscript to produce data summaries including ggplots in Excel files.
insertPlot hasn't worked under Rscript so I first print the ggplot to a png file and then use insertImage.
Unfortunately, when inserting the second image to the second sheet it also overwrites the image on the first sheet.
I end up with the same plot on all sheets.

Here a sample code:
library(ggplot2)
library(openxlsx)

d <- mtcars

p1 <- ggplot(d, aes(mpg, cyl)) + geom_point() + ggtitle("My FIRST graph")
p2 <- ggplot(d, aes(gear, carb)) + geom_point() + ggtitle("My SECOND graph")

wb <- createWorkbook()
addWorksheet(wb, "First")
png("testGraph.png", width = 1024, height = 768, units="px", res=144) #output to png device
print(p1)
dev.off()
openxlsx::insertImage(wb = wb,
sheet = "First",
file = "testGraph.png",
width = 15, height= 10, units="cm", dpi = 240
)

addWorksheet(wb, "Second")
png("testGraph.png", width = 1024, height = 768, units="px", res=144)
print(p2)
dev.off()
openxlsx::insertImage(wb = wb,
sheet = "Second",
file = "testGraph.png",
width = 15, height= 10, units="cm", dpi = 240
)
saveWorkbook(wb, file = "testInsert.xlsx", overwrite=T)

Is there a workaround for this?
Many thanks for any help

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions