I have 2 plots (created using Base graphics) and 2 data frames that I would like to combine onto one sheet in a PDF. I'm using grid.table to create a tableGrobs from my data frames. I'm having a lot of difficulty formatting the PDF output. In particular, I've been unsuccessful keeping all the objects on the same page. I want the right pannel to contain one graph, and the left panel to contain the other graph, and 2 tables below (landscape format).
Currently my code is something like the following:
library('gridExtra')
pdf("Rplots.pdf", paper = "USr", height = 8.5, width = 11)
layout(matrix(c(1,3, 2,3, 4,3), nrow = 3, ncol = 2, byrow = TRUE))
plot(myPlot1)
grid.table(df1)
plot(myPlot2)
grid.table(df2)
dev.off()
I do not want to use ggplot2.
To arrange multiple ggplot2 graphs on the same page, the standard R functions - par() and layout() - cannot be used. The basic solution is to use the gridExtra R package, which comes with the following functions: grid. arrange() and arrangeGrob() to arrange multiple ggplots on one page.
Another way to order the table in R is by converting the table into DataFrame and using the dplyr arrange() function to sort the dataframe. The arrange() function from dplyr package is also used to arrange the values in an ascending or descending order.
If layout parameters are ommitted altogether, grid. arrange() will calculate a default number of rows and columns to organise the plots. More complex layouts can be achieved by passing specific dimensions (widths or heights), or a layout matrix defining the position of each plot in a rectangular grid.
To combine base
plots and grid
objects the package gridBase
is useful.
A rough worked example base on your layout above
library(grid)
library(gridBase)
library(gridExtra)
layout(matrix(c(1,3, 2,3, 4,3), nrow = 3, ncol = 2, byrow = TRUE))
# First base plot
plot(1:10)
# second base plot
frame()
# Grid regions of current base plot (ie from frame)
vps <- baseViewports()
pushViewport(vps$inner, vps$figure, vps$plot)
# Table grob
grob <- tableGrob(iris[1:2,1:2])
grid.draw(grob)
popViewport(3)
# third base plot
plot(1:10)
# fourth
frame()
vps <- baseViewports()
pushViewport(vps$inner, vps$figure, vps$plot)
grid.draw(grob)
popViewport(3)
Which gives
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With