R - adding page numbers to PDF

后端 未结 4 851
天涯浪人
天涯浪人 2021-01-14 19:26

I\'m having trouble adding page numbers to PDFs. Here\'s how I\'m inserting pages / plots:

pdf( file = pdfFilePath , width = 11 , height = 8.5  )
for ( ...          


        
4条回答
  •  北荒
    北荒 (楼主)
    2021-01-14 20:33

    From my second comment on the Q, I suggested a base graphics solution using mtext(). This appears to work for the OP so I show an expanded version here:

    Base Graphics:

    op <- par(oma = c(2,0,0,0))
    layout(matrix(1:4, ncol = 2))
    plot(1:10)
    plot(1:10)
    plot(1:10)
    plot(1:10)
    mtext(side = 1, text = "Page 1", outer = TRUE)
    layout(1)
    par(op)
    

    Resulting in:

    base graphics page number example

    @SFun28 reports this idea works for his ggplot/grid graphics too, but it does not for me. After running the last line of the code chunk below I get the following error:

    > mtext(side = 1, text = "Page 1")
    Error in mtext(side = 1, text = "Page 1") : 
      plot.new has not been called yet
    

    which is indicative of the warning not to mix base and grid graphics.

    require(ggplot2)
    p1 <- ggplot(data.frame(X = 1:10, Y = runif(10)), aes(x = X, y = Y)) + 
            geom_point()
    vplayout <- function(x, y) {
        viewport(layout.pos.row = x, layout.pos.col = y)
    }
    grid.newpage()
    pushViewport(viewport(layout = grid.layout(2, 2)))
    print(p1, vp = vplayout(1,1))
    print(p1, vp = vplayout(1,2))
    print(p1, vp = vplayout(2,1))
    print(p1, vp = vplayout(2,2))
    mtext(side = 1, text = "Page 1")
    

提交回复
热议问题