library("grid")library("ggplotify")p1<-as.grob(~barplot(1:10))p2<-as.grob(expression(plot(rnorm(10))))p3<-as.grob(function()plot(sin))library("vcd")data(Titanic)p4<-as.grob(~mosaic(Titanic))library("lattice")data(mtcars)p5<-as.grob(densityplot(~mpg|cyl,data=mtcars))as.grob function accepts plot function call asexpression orformula, or a function thatplots to an R graphics device. The plots can be generated by basegraphics (p1,p2,p3) orgrid (p4). If the plot function producegraphic object, it can be directly used as input (p5, canbetrellis object bylattice package,meme object bymeme package,upset object by ‘UpSetR’ package,etc.).
It will convert the plot togrob object, so that it canbe compatible withgrid system and related packages.
We can now usegrid.draw to plotp1 andp2, and usepushViewport to embed plot insideanother plot.
grid.newpage()grid.draw(p1)vp=viewport(x=.35,y=.75,width=.35,height=.3)pushViewport(vp)grid.draw(p2)upViewport()If you are not family withgrid, you can useggplot2 to do similar task (e.g.p8in the below example).
All the plots that can be converted togrob aresupported to be converted toggplot object by usingas.ggplot function.
With all the plots converted toggplot objects, we areable to align plots produced by ‘base’ and ‘grid’ graphic systems usingcowplot orpatchwork.
library(cowplot)library(colorspace)col<-rainbow_hcl(3)names(col)<-unique(iris$Species)color<- col[iris$Species]p6<-as.ggplot(~plot(iris$Sepal.Length, iris$Sepal.Width,col=color,pch=15))p7<-ggplot(iris,aes(Sepal.Length, Sepal.Width,color=Species))+geom_point(shape=15)+scale_color_manual(values=col,name="")legend<-get_legend(p7)## also able to annotate base or other plots using ggplot2library(ggimage)p8<- p6+geom_subview(x=.7,y=.78,subview=legend)## Warning: `aes_()` was deprecated in ggplot2 3.0.0.## ℹ Please use tidy evaluation idioms with `aes()`## ℹ The deprecated feature was likely used in the ggimage package.## Please report the issue at <https://github.com/YuLab-SMU/ggimage/issues>.## This warning is displayed once every 8 hours.## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was## generated.p9<-as.ggplot(~image(volcano))plot_grid(p1, p2, p3, p4, p5, p6, p7, p8, p9,ncol=3,labels=LETTERS[1:9])