Search code examples
rexcelplotxlsx

how to insert a boxplot in a worksheet


I want to include boxplots in a workscheet created in R

here I found a useful way under "Add a plot into an Excel worksheet" its using the addPicture funtion but sheet <-createSheet(wb, sheetName = "boxplot") doesnt work in the lybrary xlsx and XLConnect won't install.

I tried to modify it to this:

addWorksheet(wb,  "boxplot")
    sheets <- getSheets(wb)

and now i get this error

> Error in envRefInferField(x, what, getClass(class(x)), selfEnv) :   
> ‘getNumberOfSheets’ is not a valid field or method name for reference
> class “Workbook” 
> 5. stop(gettextf("%s is not a valid field or method name for reference class %s", 
>     sQuote(field), dQuote(thisClass@className)), domain = NA) 
> 4. envRefInferField(x, what, getClass(class(x)), selfEnv) 
> 3. wb$getNumberOfSheets 
> 2. wb$getNumberOfSheets 
> 1. getSheets(doc)

Did i mess up my library's that getSheets calls a function with invalid references? Or is there an other way to save boxplots in a worksheet without the XLConnect pakage


Solution

  • Since xlsx does not seem to work for you, you could try the very useful package openxlsx (no Java dependecy, very fast, very versatile, though it only supports working with '.xlsx' files):

    install.packages("openxlsx")
    
    wb <- openxlsx::createWorkbook()
    openxlsx::addWorksheet(wb, "a_sheet_with_a_plot")
    plot(cars)
    openxlsx::insertPlot(wb, sheet = "a_sheet_with_a_plot", width = 10, height = 8, xy = NULL, startRow = 1,
                         startCol = 1, fileType = "png", units = "in", dpi = 300)
    openxlsx::saveWorkbook(wb, file = "excel_file_with_a_plot_sheet.xlsx", overwrite = TRUE)