如何在 R 中保存网格图?
How to save a grid plot in R?
我有一个网格图对象 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)
绘图效果很好,但 saving/printing 导致问题。
有什么解决方法吗?谢谢!
这是 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()
值得补充的是,更新后的 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
> class(gridAB)
[1] "gtable" "gTree" "grob" "gDesc"
预览
我有一个网格图对象 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)
绘图效果很好,但 saving/printing 导致问题。
有什么解决方法吗?谢谢!
这是 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()
值得补充的是,更新后的 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
> class(gridAB)
[1] "gtable" "gTree" "grob" "gDesc"