print to pdf file using grid.table in r - too many rows to fit on one page

后端 未结 6 1745
没有蜡笔的小新
没有蜡笔的小新 2020-12-06 11:53

I\'m trying to output a dataframe of about 40 rows and 5 columns to a .pdf file using grid.table in gridExtra package of R.

However, 40 rows is too long for a page

6条回答
  •  爱一瞬间的悲伤
    2020-12-06 12:23

    Implementing viewports from the grid is one potential solution.

    A viewport defines a region in the graphics device. It is sometimes useful to define a viewport, then push it and draw inside it. A different viewport may then be pushed and drawn inside of; this method amounts to a simple way to arrange objects on a page.

    First, define page and margin sizes.

    # Assume total page size is 8.5in x 11in
    vp.page <- viewport(x = 0.5, y = 0.5,
                       width = unit(x = 8.5, units = "inches"),
                       height = unit(x = 11, units = "inches"))
    
    # Assume 0.5in margins (i.e., 0.5 left, right, bottom, top)
    # This totals 1in for each dimension
    vp.marg <- viewport(x = 0.5, y = 0.5,
                        width = (7.5 / 8.5), height = (10 / 11))
    

    Next, Define viewports for each column.

    To arrange columns horizontally within a viewport, their x positions will be equally spaced in the interval (0,1).

    In the 2 column case, x1 = 0.25 and x2 = 0.75:

    # Define the viewport for column 1
    vp.col1 <- viewport(x = 0.25, y = 0.5, width = 0.5, height = 1)
    
    # Define the viewport for column 2
    vp.col2 <- viewport(x = 0.75, y = 0.5, width = 0.5, height = 1)
    

    Now, actual data is defined. This data will also need to be "grob'd" to be drawn into viewports.

    # Assume data is stored as `dat` and has 40 rows
    # Grob the data for column 1
    col1 <- tableGrob(dat[1:20,], rows = NULL)
    
    # Grob the data for column 2
    col2 <- tableGrob(dat[21:40,], rows = NULL)
    

    Now, draw the pdf:

    # Initiate the pdf
    pdf("results.pdf", height = 11, width = 8.5)
    # Push the viewports for page and margin
    pushViewport(vp.page); pushViewport(vp.marg)
    
    # Push column 1
    pushViewport(vp.col1)
    # Draw column 1
    grid.draw(col1)
    
    # Return to the previous viewport
    upViewport()
    
    # Push the viewport for column 2
    pushViewport(vp.col2)
    # Draw column 2
    grid.draw(col2)
    
    # End the pdf and save it
    dev.off()
    

提交回复
热议问题