1 min read

Math Expressions with Facets in ggplot2

In this post I show how we can use $\LaTeX$ math expressions to label the panels in facets to produce the following plot:

The updated version of ggplot2 V 2.0 has improved the way we can label panels in facet plots with the use of a generic labeller function. The latex2exp package has made it much easier to write $\LaTeX$ expressions in R.

You will need to load the following packages for the code below to work:

  1. devtools
  2. ggplot2
  3. latex2exp

I have posted some sample data in a GitHub Gist which you can import into your R session using the source_gist function from the devtools package:

Then we create a labelling function which takes as input a string and prepends $\log(\lambda_{\gamma})$ to it. Note that latex2exp::TeX is the workhorse function that parses $\LaTeX$ syntax so that R understands it. Otherwise it becomes very messy to try and write more complex math expressions in R.

The code to produce the plot above is given by:

Note that we need to provide the default = label_parsed argument to the facet_wrap function so that it interprets the result from the appender function as math expressions.