【问题标题】:Combine base and ggplot graphics in R figure window in different pages在不同页面的R图形窗口中组合base和ggplot图形
【发布时间】:2015-08-24 13:58:24
【问题描述】:

我使用this solution 将 R 绘图和 ggplot 组合在一起,然后在循环中使用它来将其中的一个打印到不同页面的 pdf 中。但是由于某种原因,每个新页面的边距都会变大,并且在某些时候图会消失。我该如何纠正?谢谢

【问题讨论】:

    标签: r pdf plot ggplot2


    【解决方案1】:

    我可以重现错误。解决方案,添加(推送视口)viewport 到视口树以插入网格图。但它忘记删除它(弹出视口)。

    在 ned 处添加行将解决问题:

    popViewport()
    

    测试解决方案:

    为了测试此修复,我将绘图代码包装在一个函数中并复制它以生成多页 pdf。

    初始化变量

    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)
    

    绘图功能

    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
      }
    

    创建多页pdf

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

    【讨论】:

    • 效果很好。谢谢。
    猜你喜欢
    • 2012-12-16
    • 2017-05-21
    • 1970-01-01
    • 2013-06-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多