R: deleting ggplot2 object does not free space? Possible memory leakage?

Viewed 134

I notice that when trying to remove a ggplot2 object from the user workspace, there is still a lot of memory used!? In the example below, deleting a pseudo ggplot call using a 400MB dataset still leaves 400MB used. This seems to happen in particular when the data used in the ggplot2 call is directly read from file.

Is this expected behavior, or could that be a memory leakage Hadley talks about in Advanced R? And how can I effectively clear the memory (gc() won't help)?

Note that this is possibly related to Memory leakage in using `ggplot` on large binned datasets, but that post never received an answer.

Thanks!

pryr::mem_used()
path <- tempfile() 
if(!file.exists(path)){
  saveRDS(as.data.frame(matrix(1:1e08, ncol=5)), path)
}

## memory leak
pryr::mem_used()
#> 34.9 MB
p1 <- ggplot2::ggplot(readr::read_rds(path), ggplot2::aes(V1))
rm(p1)
invisible(gc())
pryr::mem_used()
#> 447 MB
ls()
#> [1] "path"

Created on 2020-11-02 by the reprex package (v0.3.0)

1 Answers

Note that ggplot tracks the last plot created in a cache in the package namespace. It can be retrieved by ggplot2::last_plot() and is there so functions like ggsave() can work without you having to explicitly pass the plot to the function. You can clear that out with

ggplot2::set_last_plot(NULL)

So for example

pryr::mem_used()
p1 <- ggplot2::ggplot(readr::read_rds(path), ggplot2::aes(V1))
rm(p1)
ggplot2::set_last_plot(NULL)
invisible(gc())
pryr::mem_used()

The cache is set anytime you call ggplot() or when a ggplot object is printed. It only stores the most recent value.

Related