Make your trellis the trillest

Michael Chimento
Source Filter
Published in
2 min readMay 20, 2017

Trellis plots are a useful tool for visualizing nested data in an organized way. It lets a reader quickly compare data between subjects or subsets without throwing everything onto one graph.

The lattice package for R provides the function xyplot() to make trellis plots using base R graphics. Unfortunately, they end up looking a bit too dull and utilitarian. Below is some example code with plots using a dataset on global fertility rates. We will be using the following variables:

  • Country
  • Continent
  • Fertility: as measured by births per woman
  • Period: year of observation

Let’s say I want to get a broad picture of changes in fertility rate over time using a trellis plot. I’ll start by making a quick and dirty plot by country.

library("lattice")fert = read.csv("/fert-climate.csv")xyplot(fertility ~ period | Country, data=fert)

Holy christ it’s ugly and uninformative. But, I can hazard there might be differences in trends between continents, as almost all european countries look near flat. Let’s make another visualization by continent.

xyplot(fertility ~ period | continent, data=fert)

This is also pretty horrible, giving only the shape of the data without allowing you to keep track of individual countries. After spending 20 mins googling I couldn’t find any easy way of replacing these dots with color coded lines.

ggplot2 to the rescue! You can easily achieve an informative trellis plot using qplot() and facet_wrap() that looks infinitely better, imo.

library(ggplot2)qplot(period, fertility, data= fert, 
colour = Country, geom = "line")
+ facet_wrap(~ continent)

It could use additional formatting, but this is a definite improvement with little effort.

--

--