R - adding page numbers to PDF

后端 未结 4 842
天涯浪人
天涯浪人 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:15

    I have modified an example from Paul Murrell's R Graphics book that draws an entire plot using grid and then places a label at the bottom in a separate viewport. I leave the fine tuning to the OP as I don't know what the individual plots are doing, but the general idea of creating an extra viewport (?) across the bottom of the device into which the label is drawn should map onto the grid.layout() ideas already used by @SFun28:

    label <- textGrob("A page number! ",
                      x=0.5, y = 1.0, just="centre")
    x <- seq(0.1, 0.9, length=50)
    y <- runif(50, 0.1, 0.9)
    gplot <- 
      gTree(
        children=gList(rectGrob(gp=gpar(col="grey60",
                                        fill="white")),
                       linesGrob(x, y), 
                       pointsGrob(x, y, pch=16, 
                                  size=unit(1.5, "mm"))),
        vp=viewport(width=unit(1, "npc") - unit(5, "mm"), 
                    height=unit(1, "npc") - unit(10, "mm")))
    
    
    
    layout <- grid.layout(2, 1,
                          widths=unit(c(1, 1), 
                                      c("null", "grobwidth"),
                                      list(NULL, label)),
                          heights = unit(c(1, 1),
                                         c("null", "grobheight"),
                                         list(NULL, label)))
    
    grid.rect(gp=gpar(col="grey60", fill="grey90"))
    pushViewport(viewport(layout=layout))
    pushViewport(viewport(layout.pos.row=2))
    grid.draw(label)
    popViewport()
    pushViewport(viewport(layout.pos.col=1))
    grid.draw(gplot)
    popViewport(2)
    

    Which gives:

    A grid page number example

提交回复
热议问题