2

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?

justinian482
  • 845
  • 2
  • 10
  • 18
  • 2
    The `eulerr` plot method uses `grid` graphics, where by convention plotting functions produce objects which are not displayed until you print them. – user2554330 Jul 05 '23 at 08:29

1 Answers1

4

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

SamR
  • 8,826
  • 3
  • 11
  • 33