eulerr plot does not work when executed inside a function

53 Views Asked by At

I want to create an euler plot inside a function with the eulerr package:

library(eulerr)

test <- function(listA,listB,file,labels,title){
  euler <- euler(list("A"=listA, "B"=listB))
  
  #plot euler object and save to file
  pdf(paste0("euler/",file,".pdf"))
  plot(euler,
       "quantities"=TRUE,
       "labels"=labels,
       "main"=title)
  dev.off()
}

test(c("A","B","C","D"),
     c("C","D","E","F","G"),
     "test",
     c("list A","list B"),
     "TITLE")

It runs without an error, but the test.pdf file is empty.

When I run it outside a function I get the plot I wanted:

library(eulerr)

listA <- c("A","B","C","D")
listB <- c("C","D","E","F","G")
labels <- c("list A","list B")
file <- "test"
title <- "TITLE"

euler <- euler(list("A"=listA, "B"=listB))
  
#plot euler object and save to file
pdf(paste0("euler/",file,".pdf"))
plot(euler,
     "quantities"=TRUE,
     "labels"=labels,
     "main"=title)
dev.off()

enter image description here

I must be missing something really obvious but what am I doing wrong?

1

There are 1 best solutions below

0
On BEST ANSWER

You need to add print() around your plot. See the R FAQ:

The print() method for the graph object produces the actual display. When you use these functions interactively at the command line, the result is automatically printed, but in source() or inside your own functions you will need an explicit print() statement

test <- function(listA, listB, file, labels, title) {
    euler <- euler(list("A" = listA, "B" = listB))
    p <- plot(euler,
        "quantities" = TRUE,
        "labels" = labels,
        "main" = title
    )

    # plot euler object and save to file
    pdf(paste0("euler/", file, ".pdf"))
    print(p)
    dev.off()
}
test(listA, listB, file, labels, title) # saves the plot below to pdf

enter image description here