我有一个网格图对象g。
class(g)
"gtable" "grob" "gDesc"
我可以使用grid.draw(g)绘制情节。但是,我无法找到将绘图保存为pdf文件的方法。
我试过了:
ggsave(g, file="plot.png")
但显然ggsave并没有在这样的对象上工作。
以下是?grid.draw帮助页面中的示例:
grid.newpage()
## Create a graphical object, but don't draw it
l <- linesGrob()
## Draw it
grid.draw(l)
绘图效果很好,但保存/打印会导致问题。
有关此问题的解决方法吗?谢谢!
答案 0 :(得分:8)
这就是MrFlick回答的问题,但对于PDF(您在问题中提出的要求)。
## 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
dev.off()
答案 1 :(得分:6)
可能值得添加更新的ggsave
版本,以便设置所需的导出。
# Load
lapply(c("ggplot2",
"gridExtra"),
require,
character.only = TRUE)
sessionInfo()
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] gridExtra_2.2.1 ggplot2_2.1.0
loaded via a namespace (and not attached):
[1] colorspace_1.2-6 grid_3.1.1 gtable_0.2.0 munsell_0.4.3 plyr_1.8.3 Rcpp_0.12.6
[7] scales_0.4.0 tools_3.1.1
a <- ggplot(data = mtcars) +
geom_point(aes(x = mpg, y = cyl))
b <- ggplot(data = mtcars) +
geom_line(aes(x = wt, y = vs))
# grid
gridAB <- grid.arrange(a, b)
# Export
ggsave(filename="ab.pdf", plot=gridAB)
> class(gridAB)
[1] "gtable" "gTree" "grob" "gDesc"