xiaoxiao87 xiaoxiao87 - 4 months ago 38
R Question

How to save a grid plot in R?

I have a grid plot object g.

"gtable" "grob" "gDesc"

I can use grid.draw(g) to draw the plot. However, I cannot figure out a way to save the plot to a pdf file.

I tried:

ggsave(g, file="plot.png")

But apparently ggsave doesn't work on such an object.

Here is an example from the ?grid.draw help page:

## Create a graphical object, but don't draw it
l <- linesGrob()
## Draw it

Drawing works well, but saving/printing causes the problem.

Any workaround on this? Thanks!


This is what MrFlick answered, but for PDFs (what you asked for in your question).

## Initiate writing to PDF file
pdf("path/to/file/PDFofG.pdf", height = 11, width = 8.5, paper = "letter")

## Create a graphical object g here
g # print it

## Stop writing to the PDF file