TikZ diagrams with R: loops with tikzDevice

Recently I needed to create a lot of similar charts for input into a LaTeX document.  In this post, I will show how I integrated the R package tikzDevice with usepackage{tikz} and a simple R loop to facilitate the task of creating tens (or hundreds) of publish-ready diagrams.  For an introduction to using tikzDevice, see this earlier post.

The approach I will use is as follows:

  1. Create a plot in R.
  2. Create a loop in R that will generate multiple diagrams for different subsets of my data.
  3. Integrate tikzDevice with the loop to output diagrams as TikZ code in a .tex file in the directory of my LaTeX document.
  4. Include the documents in my LaTeX file.

For this example, we’ll be using the panel.xls data set from Walter Enders’ web site, showing quarterly values of the real effective exchange rates (CPI-based) for Australia, Canada, France, Germany, Japan, Netherlands, the United Kingdom and the USA between Q1 1980 and Q1 2008. For more commentary, see page 245 of his text “Applied Econometric Time Series”, 3rd edition.

To quickly graph all the series together, we could do the following:


[sourcecode language=”r”]
# gdata helps read .xls files
df = read.xls("http://cba.ua.edu/assets/docs/wenders/panel.xls", sheet = 1)

# a quick plot of all countries
df2 = ts(df, frequency = 4, start = c(1980, 1))
plot(df2[,-1], main = ‘Quarterly Effective Exchange Rates, 1980-2008’, col = ‘blue’)

Or, to create a chart similar to the one shown at the top of this post we could do the following:
Continue reading “TikZ diagrams with R: loops with tikzDevice”