## 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:

### R:

# gdata helps read .xls files
require(gdata)
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:

# convert quarterly data into "Date" format
df\$Date = as.Date(yearqtr(1980 + seq(0, 28*4)/4),frac = 1)

# reshape is useful when using ggplot
require(reshape)
dfgg = melt(df, id.var = 'Date')
names(dfgg) = c('Date','Country','CPI')

# ggplot offers some nice looking charts
require(ggplot2)

# plot all time series on one chart, using different colors
ggplot(dfgg, aes(x=Date, y=CPI, group=Country)) + geom_line(aes(colour = Country))


#### Creating multiple images efficiently

However, the topic of this post is to create several images, and output them either (a) to a .tex file, or (b) to a bunch of different .jpg or .pdf files.

## Outputting .pdf files

Our goal will be to output a single .pdf file for each country.

i = 2
for (i in 2:ncol(df)) {

subs = NULL
subs = subset(df, select = c(1,i))

pdf(paste(names(subs)[2],'.pdf',sep=''), width = 7, height = 4)
plot(subs, type = 'l', col = 'blue', ylab = 'CPI', main = paste(names(subs)[2]))

dev.off()

}


## Outputting as TikZ code into single .tex file

Here is the simple way:

require(tikzDevice)
dev.new()

i = 2
tikz( 'CPI_by_countries.tex' )
for (i in 2:ncol(df)) {

subs = NULL
subs = subset(df, select = c(1,i))

plot(subs, type = 'l', col = 'blue', ylab = 'CPI', main = paste(names(subs)[2]))

}

dev.off()


Here is a bit more complex way that also puts each plot into its own figure, then gives each a caption and reference tag:

fn if(file.exists(fn)) file.remove(fn)

i = 2
for (i in 2:ncol(df)) {     #begin LOOP

subs = NULL
subs = subset(df, select = c(1,i))

cat("\\begin{figure}\n", file = fn, append=TRUE)
sink(fn, append=TRUE)
tikz(console = TRUE)

plot(subs, type = 'l', col = 'blue', ylab = 'CPI', main = paste(names(subs)[2]))

dev.off()
sink()
cat(paste("\\caption{CPI - ",paste(names(subs)[2]),"}\\label{fig:",
paste(names(subs)[2]),"}\n",sep=""), file = fn, append=TRUE)
cat("\\end{figure}\n", file = fn, append=TRUE)

}         #end LOOP


Then, add the code \include{CPI_by_countries} to your LaTeX document, and make sure the .tex file is in the same folder. See an earlier post for more information on using R and LaTeX together.