ggplot2 Version of Figures in “Lattice: Multivariate Data Visualization with R” (Part 1)
The data visualization package lattice is part of the base R distribution, and like ggplot2 is built on Grid graphics engine. Deepayan Sarkar’s (the developer of lattice) book Lattice: Multivariate Data Visualization with R gives a detailed overview of how the package works. All the figures and code used to produce them is also available on the book website.
In order to give those interested an option to compare graphs produced by ggplot2 and lattice, I will attempt to recreate the book’s lattice graphs in ggplot2. There are 14 chapters in the book, so this means that there would be at least 13 more posts on the subject.
The output of both packages can be tweaked so that the graphs would look similar if not the same, however for the purposes of comparison, the standard settings (at least in ggplot2) are used when possible. The code used to create the images is in separate paragraphs, allowing easy comparison, and by clicking on the thumbnail, a bigger image file is also available.
Chapter 1 – Introduction
Topics covered:
- Basic usage; high level functions
- Conditioning
- Superposition (a.k.a. grouping)
- “trellis” objects
Figure 1.1
> library(lattice) > library(ggplot2) > data(Chem97, package = "mlmRev") |
lattice
> pl <- histogram(~gcsescore | factor(score), data = Chem97) > print(pl) |
ggplot2
> pg <- ggplot(Chem97, aes(gcsescore)) + geom_histogram(binwidth = 0.5) + + facet_wrap(~score) > print(pg) |
| Note | ggplot2 uses counts, not percentages by default. |
| Note | ggplot2 plots the facets starting from top-left, lattice starts from bottom-left. |
Figure 1.2
lattice
> pl <- densityplot(~gcsescore | factor(score), data = Chem97, + plot.points = FALSE, ref = TRUE) > print(pl) |
ggplot2
> pg <- ggplot(Chem97, aes(gcsescore)) + stat_density(geom = "path", + position = "identity") + facet_wrap(~score) > print(pg) |
Figure 1.3
lattice
> pl <- densityplot(~gcsescore, data = Chem97, groups = score, + plot.points = FALSE, ref = TRUE, auto.key = list(columns = 3)) > print(pl) |
ggplot2
> pg <- ggplot(Chem97, aes(gcsescore)) + stat_density(geom = "path", + position = "identity", aes(colour = factor(score))) > print(pg) |






Awesome idea! Thanks for doing this.
I concur with Hadley. I’ve been doing most of my R graphics with the help of this book, so seeing the ggplot2 versions is a very good learning tool!
+1 awesome!!!
Much appreciate. This is very helpful.