convert base plot to grob object

knitr::opts_chunk$set(tidy = FALSE,
           message = FALSE)
library("ggplot2")
library("cowplot")
library("grid")
library("base2grob")
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
ggsave(p1, filename = f)
file.info(f)$size

## we can even directly using formula or expression of base plot command inside ggsave
ggsave(~pie(1:3), filename = f)
file.info(f)$size

## even function is supported
ggsave(function() plot(sqrt), filename = f)
file.info(f)$size

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])


Try the base2grob package in your browser

Any scripts or data that you put into this service are public.

base2grob documentation built on May 2, 2019, 3:31 p.m.