R ggplot2 saving plots as R objects and displaying in grid

In the following reproduceable example I try to create a function for a ggplot distribution plot and saving it as an R object, with the intention of displaying two plots in a grid.

ggplothist<- function(dat,var1)
{
        if (is.character(var1)) {
            var1 <- which(names(dat) == var1) 
    }
    distribution <- ggplot(data=dat, aes(dat[,var1])) 
    distribution <- distribution  + geom_histogram(aes(y=..density..),binwidth=0.1,colour="black", fill="white")
    output<-list(distribution,var1,dat)
    return(output)
}

Call to function:

set.seed(100)
df  <- data.frame(x = rnorm(100, mean=10),y =rep(1,100))    
output1 <- ggplothist(dat=df,var1='x')
output1[1]

All fine untill now.

Then i want to make a second plot, (of note mean=100 instead of previous 10)

df2  <- data.frame(x = rep(1,1000),y = rnorm(1000, mean=100))    
output2 <- ggplothist(dat=df2,var1='y')
output2[1]

Then i try to replot first distribution with mean 10.

output1[1]

I get the same distibution as before? If however i use the information contained inside the function, return it back and reset it as a global variable it works.

var1=as.numeric(output1[2]);dat=as.data.frame(output1[3]);p1 <- output1[1]
p1

If anyone can explain why this happens I would like to know. It seems that in order to to draw the intended distribution I have to reset the data.frame and variable to what was used to draw the plot. Is there a way to save the plot as an object without having to this. luckly I can replot the first distribution.

but i can't plot them both at the same time

 var1=as.numeric(output2[2]);dat=as.data.frame(output2[3]);p2 <- output2[1]
 grid.arrange(p1,p2)

ERROR: Error in gList(list(list(data = list(x = c(9.66707664902549, 11.3631137069225, : only 'grobs' allowed in "gList"

In this" Grid of multiple ggplot2 plots which have been made in a for loop " answer is suggested to use a list for containing the plots

 ggplothist<- function(dat,var1)
{
    if (is.character(var1)) {
            var1 <- which(names(dat) == var1) 
    }
    distribution <- ggplot(data=dat, aes(dat[,var1])) 
    distribution <- distribution  + geom_histogram(aes(y=..density..),binwidth=0.1,colour="black", fill="white")
    plot(distribution)
    pltlist <- list()
    pltlist[["plot"]] <- distribution
    output<-list(pltlist,var1,dat)
    return(output)
}

output1 <- ggplothist(dat=df,var1='x')
p1<-output1[1]

output2 <- ggplothist(dat=df2,var1='y')
p2<-output2[1]

output1[1]

Will produce the distribution with mean=100 again instead of mean=10 and:

grid.arrange(p1,p2)

will produce the same Error

Error in gList(list(list(plot = list(data = list(x = c(9.66707664902549, : only 'grobs' allowed in "gList"

As a last attempt i try to use recordPlot() to record everything about the plot into an object. The following is now inside the function.

    ggplothist<- function(dat,var1)
{
    if (is.character(var1)) {
            var1 <- which(names(dat) == var1) 
    }
    distribution <- ggplot(data=dat, aes(dat[,var1])) 
    distribution <- distribution  + geom_histogram(aes(y=..density..),binwidth=0.1,colour="black", fill="white")
    plot(distribution)
    distribution<-recordPlot()
    output<-list(distribution,var1,dat)
    return(output)
}

This function will produce the same errors as before, dependent on resetting the dat, and var1 variables to what is needed for drawing the distribution. and similarly can't be put inside a grid.

I've tried similar things like arrangeGrob() in this question "R saving multiple ggplot2 plots as R-object in list and re-displaying in grid " but with no luck.

I would really like a solution that creates an R object containing the plot, that can be redrawn by itself and can be used inside a grid without having to reset the variables used to draw the plot each time it is done. I would also like to understand wht this is happening as I don't consider it intuitive at all.

The only solution I can think of is to draw the plot as a png file, saved somewhere and then have the function return the path such that i can be reused - is that what other people are doing?.

Thanks for reading, and sorry for the long question.


Found a solution

How can I reference the local environment within a function, in R?

by inserting

localenv <- environment() 

And referencing that in the ggplot

distribution <- ggplot(data=dat, aes(dat[,var1]),environment = localenv)

made it all work! even with grid arrange!

链接地址: http://www.djcxy.com/p/30878.html

上一篇: grid.arrange与R Studio中的filled.contour

下一篇: R ggplot2将绘图保存为R对象并以网格显示