library("grid")
library("base2grob")
p1 <- base2grob(~barplot(1:10))
p2 <- base2grob(expression(plot(rnorm(10))))
p3 <- base2grob(~pie(1:5))
p4 <- base2grob(function() plot(sin))
base2grob
function accepts base plot function call as expression
or formula
, or a function that plots to an R graphics device. It will convert the plot to grob
object, so that it can be compatible with grid
system and related packages.
grid
We can now use grid.draw
to plot p1
and p2
, and use pushViewport
to embed plot inside another plot.
grid.newpage()
grid.draw(p1)
vp = viewport(x=.35, y=.75, width=.35, height=.3)
pushViewport(vp)
grid.draw(p2)
upViewport()
ggsave
The object is compatible with ggplot2::ggsave()
and can be exported to file using ggsave()
:
library(ggplot2)
f <- tempfile(fileext = ".pdf")
f
## [1] "/var/folders/zy/t6vrjxss73s4wc07dp52z6680000gn/T//Rtmpn4h0Vw/file1b7e5163c383.pdf"
ggsave(p1, filename = f)
file.info(f)$size
## [1] 4333
## we can even directly using formula or expression of base plot command inside ggsave
ggsave(~pie(1:3), filename = f)
file.info(f)$size
## [1] 5464
## even function is supported
ggsave(function() plot(sqrt), filename = f)
file.info(f)$size
## [1] 5094
plot_grid
We can now use cowplot::plot_grid()
to align base plots.
library(cowplot)
p5 <- base2grob(~image(volcano))
p6 <- qplot(rnorm(10), rnorm(10)) + theme_grey()
plot_grid(p1, p2, p3, p4, p5, p6, ncol=3, labels=LETTERS[1:6])