Increase in memory usage while storing plots to png image in R

17 views
Skip to first unread message

Suparna Jayaprakash

unread,
Dec 29, 2016, 8:02:59 AM12/29/16
to ggplot2

The code given below is used to store some plots to a png image.


library(pryr)
library(grid)
library(gridExtra)
library(ggplot2)

for (i in c(1:10000)){
    print(mem_change({
        m = 1
        sd = 2
        p1 <- qplot(1:3000,rnorm(3000, m, sd))
        p2 <- qplot(1:300,rnorm(300, m, sd))
        p3 <- qplot(1:1400,rnorm(1400, m, sd))
        p4 <- qplot(1:2030,rnorm(2030, m, sd))
        p5 <- qplot(1:102,rnorm(102, m, sd))
        p6 <- qplot(1:110,rnorm(110, m, sd))

        lay=rbind(
            c(NA,1,NA,4),
            c(NA,NA,NA,NA),
            c(NA,2,NA,5),
            c(NA,NA,NA,NA),
            c(NA,3,NA,9),
            c(NA,NA,NA,NA)
        )
        gs=list(p1,p2,p3,p4,p5,p6)
        png(filename=paste0("plot_",as.character(i),".png"), bg="white",width = 8.5, height = 9.7,units="in",res=300)
        grid.arrange(
            grobs=gs,
            layout_matrix = lay,
            heights=unit(c(2.65,0.25,2.65,0.1,1.5,2),c(rep("in",4))),
            widths=unit(c(0.5,3,0.5,2.75),c(rep("in",4))),
        )
        dev.off()
        print("mem change per loop")
    }))
}

While running this code some memory(around 10-20 kBs) is lost in each iteration. As it is a big loop, memory usage grows to a large value. How to solve this problem?
This happens only while using ggplot2. There is no problem with simple plot function.
Reply all
Reply to author
Forward
0 new messages