Mixing ggplot2 graphs with other graphical output - brodieG/ggplot2 GitHub Wiki

ggplot2 is based on Grid graphics, and is therefore mostly incompatible with standard R graphics functions. In particular,

  • par() is without effect to specify a layout (mfrow, etc.)
  • idem for layout() and split.screen()
  • standard R graphics such as plot(), image(), hist() will not easily be placed on the same device as a ggplot2 graph. The gridBase package may offer some help in this regard, however.

The Grid graphics system is more flexible and powerful than standard R graphics, however, and many of the base functions are available in one form or another in the grid, lattice, or vcd packages. A couple of additional Grid functions is available in the gridExtra and RGraphics packages.

Layout multiple ggplots on a single page

ggplot2 has a powerful facetting system that allows complex bidimensional arrangements of plot panels on a single page. In some cases, however, it is useful to place side-by-side several different plots not linked by facetting. It can also be the case that one wishes to add an inset to a larger plot. In all these cases, ggplots have to be placed on the page using the Grid viewport system.

The gridExtra package provides a wrapper function for the most common case, where one wishes to arrange several plots on a rectangular grid,

library(ggplot2)
p1 = qplot(1:10,rnorm(10))
p2 = qplot(1:10,rnorm(10))
library(gridExtra)
grid.arrange(p1, p2, ncol=2, main = "Main title")

Place a foreign graphical element inside a ggplot

ggplot2 (>0.9.0) provides new geoms, annotation_custom() and annotation_raster that can be used to decorate a ggplot2 with an external graphical element ("grob", in Grid terminology), such as a table or an image, or even a plot itself (inset).

p = qplot(1:10, 1:10) + theme_bw()
g = ggplotGrob(qplot(1, 1))
p + annotation_custom(grob = g, xmin = 2, xmax = 4, ymin = 6, ymax = 10)

Add tables and/or text summary beside a ggplot

A basic text summary can be added next to a ggpot2 using viewports. Useful functions to add text to a graphic device in the Grid graphics framework include the tableGrob function in package gridExtra and splitTextGrob in package RGraphics.

library(RGraphics) # support of the "R graphics" book, on CRAN
library(gridExtra) 
g1 <- tableGrob(head(iris))
string <- "
This famous (Fisher's or Anderson's) iris data set gives the
measurements in centimeters of the variables sepal length and width
and petal length and width, respectively, for 50 flowers from each of
3 species of iris. The species are Iris setosa, versicolor, and
virginica.
"
g2 <- splitTextGrob(string)
#"Sepal.Length" "Sepal.Width"  "Petal.Length" "Petal.Width"  "Species"
g3 <- qplot(Sepal.Length,  Petal.Length, data=iris, colour=Species)
grid.arrange(g1, g2, g3, ncol=1, main="The iris data")