Combine base and ggplot graphics in R figure window in different pages

812 views Asked by At

I used this solution to combine an R plot and ggplot and then used it in a loop to print a of these to a pdf in different pages. But for some reason the margins get bigger in every new page and at some point plots disappear. How can I correct that? Thanks enter image description here

1

There are 1 answers

0
agstudy On BEST ANSWER

I can reproduce the bug. The solution , add (push viewport) a viewport to the vieport tree to insert the grid plot. But it forget to remove it ( pop viewport).

Adding the line at the ned will fix the problem :

popViewport()

Test the solution:

To test this fix, I wrap the plot code in a function and repliacte it to produce a multi-pages pdf.

init variables

library(gridBase)
library(biwavelet)
library(grid)
library(ggplot2)
t <- c(1:(24*14)) 
P <- 24 
A <- 10 
y <- A*sin(2*pi*t/P)+20

t1 <- cbind(t, y)
wt.t1=wt(t1)

the plot function

combine_base_grid <-
  function(){

    par(mfrow=c(2, 2))
    plot(y,type = "l",xlab = "Time (hours)",ylab = "Amplitude",main = "Time series")
    plot(wt.t1, plot.cb=FALSE, plot.phase=FALSE,main = "Continuous wavelet transform",
         ylab = "Period (hours)",xlab = "Time (hours)")
    spectrum(y,method = "ar",main = "Spectral density function", 
             xlab = "Frequency (cycles per hour)",ylab = "Spectrum")
    ## the last one is the current plot
    plot.new()              ## suggested by @Josh
    vps <- baseViewports()
    pushViewport(vps$figure) ##   I am in the space of the autocorrelation plot
    vp1 <-plotViewport(c(1.8,1,0,1)) ## create new vp with margins, you play with this values 
    acz <- acf(y, plot=F)
    acd <- data.frame(lag=acz$lag, acf=acz$acf)
    p <- ggplot(acd, aes(lag, acf)) + geom_area(fill="grey") +
      geom_hline(yintercept=c(0.05, -0.05), linetype="dashed") +
      theme_bw()+labs(title= "Autocorrelation\n")+
      ## some setting in the title to get something near to the other plots
      theme(plot.title = element_text(size = rel(1.4),face ='bold'))
    print(p,vp = vp1) 
    popViewport()           ## THE FIX IS JUST THIS LINE
  }

create a multi page pdf

pdf("plots.pdf")
replicate(3,combine_base_grid())
dev.off()