Reputation: 1
I am encountering a problem when saving a ggplot to pdf. I would like to plot two ggplot2 images side by side to a pdf using pdf(). However no content appears in the pdf. Is there any way to use grid.arrange() objects together with pdf()
Sample code to reproduce the problem:
library(ggplot2)
library(gridExtra)
p1<-ggplot(mtcars, aes(mpg))+stat_ecdf()
p2<-ggplot(mtcars, aes(cyl))+stat_ecdf()
p3<-grid.arrange(p1,p2, ncol=2)
pdf(file="plot.pdf")
p3
dev.off()
Upvotes: 0
Views: 260
Reputation: 20444
When you call grid.arrange()
it prints the plot but it does not return the plot. It returns a gtable
object:
class(p3)
# [1] "gtable" "gTree" "grob" "gDesc"
If you try to print it you will see that:
p3
# TableGrob (1 x 2) "arrange": 2 grobs
# z cells name grob
# 1 1 (1-1,1-1) arrange gtable[layout]
# 2 2 (1-1,2-2) arrange gtable[layout]
If you want to write the plot to a pdf
, you can do:
pdf(file="plot.pdf")
grid.arrange(p1,p2, ncol=2)
dev.off()
Upvotes: 1