July 12, 2011

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

Tags: , ,
June 29, 2011

## TikZ diagrams with R: A Normal probability distribution function

You may have seen an earlier post where I went through some examples of how to create a normal distribution in LaTeX using TikZ. In this post, I will show a different way to accomplish a similar result using R and the package tikzDevice().

tikzDevice() is an R package that outputs any image from R as TikZ code in a .tex file. In order to include the outputted .tex file in you LaTeX document, you need to do two things:

• add \usepackage{tikz} in the preamble to your LaTeX document.
• add \include{normal_pdf} where you’d like your image (after you’ve created and outputted normal_pdf.tex from R, as shown below).

#### R:

# load tikzDevice package
require(tikzDevice)

# Choose boundaries to be shaded in blue
a = 0.5
b = 1.8

# creates x & y boundaries based on a and b parameters
x.val <- c(a,seq(a,b,0.01),b)
y.val <- c(0,dnorm(seq(a,b,0.01)),0)

# choose the name and location for your .tex file
# it should be the same directory as your latex document
tikz( '/Users/kevingoulding/latex_documents/thesis/normal_pdf.tex' )

# plots a normal distribution curve
curve(dnorm(x,0,1),xlim=c(-3,3),main='The Standard Normal PDF',
xlab = '$x$', ylab = '$f(x)$',
frame.plot = FALSE, axes = FALSE)

# shades in a polygon underneath curve
polygon(x.val,y.val,col='skyblue')

# creates blank axes
Axis(side=1, labels=FALSE)
Axis(side=2, labels=FALSE)

# must turn device off to complete .tex file
dev.off()

Tags: , , ,
June 25, 2011

## TikZ diagrams with R: tikzDevice

There are several options for integrating your R workspace with LaTeX. One of these is the R package tikzDevice that allows you to export images created in R as tikz code in a .tex file, for immediate use in a LaTeX document via the line \include{diagrams}.

A simpler way, the one we all start out with, is to export an image from R as a .pdf, then include it using the line \includegraphics{diagrams.pdf}. This is a pretty easy and straightforward workflow – so, why would I want to use tikzDevice?

There several advantages to converting your images into TikZ code directly from R:

1. TikZ diagrams consist of vectors coded directly into your LaTeX document: there’s no loss of image resolution.
2. The labels on TikZ diagrams match the font of your LaTeX document.
3. Wonderful LaTeX equations can be effortlessly used as labels in your diagrams.
4. You can harness the power of the loop in R to create a single .tex file containing many images.
5. You can harness the power of the loop in R to add \caption{} and \label{} lines to all your images for immediate reference within LaTeX.
6. You can include all these features and output via one line in LaTeX: \include{diagrams}.

## A Simple Example

That being said, let’s export a TikZ scatterplot using the tikzDevicepackage. We will use data posted on Dr. Walter Enders web site.

Notice the fancy latex equations as labels on the plot.

#### R:

# gdata helps read .xls files
require(gdata)
df = read.xls("http://cba.ua.edu/assets/docs/wenders/arch.xls", sheet = 1)

# tikzDevice will export the plots as a .tex file
require(tikzDevice)

# choose a name and path for the .tex file
# folder should be the same as where your latex document resides
tikz( '/Users/kevingoulding/latex_documents/thesis/plot_with_line.tex' )

plot(df, xlab = "$\\alpha_t + \\hat{\\beta}X_t$", ylab = "$Y_t$",
main = "$Y_t = \\alpha_t + \\hat{\\beta}X_t$")
abline(h = mean(df[,2]), col = "red", lwd = 2)

dev.off()					# must turn device off to complete .tex file


To include this diagram in your LaTeX document, simply add the line \include{plot_with_line} and compile. Don’t forget to include \usepackage{tikz} in the preamble. If you zoom in, you can see that we’ve labeled the plot and axes using LaTeX math language (amsmath).

A few things to be careful with as you try to code LaTeX equations from within R:

• All backslashes need to be doubled. \ –> \\.
• All equations still need to be bordered by $ on each side. To be continued… Tags: , , June 19, 2011 ## TikZ for economists: A how-to guide with examples Below is a guide I created to assist economists in quickly creating economics diagrams using the package TikZ in LaTeX. Thoughts, comments, ideas? Let me know; I’m always appreciative of feedback. Correspondence via e-mail can be directed to kevingoulding [at] gmail {dot} com. Tags: , , June 17, 2011 ## TikZ diagrams for economists: A normal pdf with shaded area. I have been dabbling with the TikZ package to create some diagrams relevant to a first year microeconomics course. The following diagram of the probability density function (pdf) of a normal distribution may be useful to others wishing to integrate similar diagrams into their LaTeX documents or Beamer presentations. To use, insert the following code anywhere you like within a .tex document (you must include \usepackage{tikz} in your header): ## The Cumulative Density of $y$ #### INSERT INTO .TEX DOCUMENT \begin{tikzpicture} % define normal distribution function 'normaltwo' \def\normaltwo{\x,{4*1/exp(((\x-3)^2)/2)}} % input y parameter \def\y{4.4} % this line calculates f(y) \def\fy{4*1/exp(((\y-3)^2)/2)} % Shade orange area underneath curve. \fill [fill=orange!60] (2.6,0) -- plot[domain=0:4.4] (\normaltwo) -- ({\y},0) -- cycle; % Draw and label normal distribution function \draw[color=blue,domain=0:6] plot (\normaltwo) node[right] {}; % Add dashed line dropping down from normal. \draw[dashed] ({\y},{\fy}) -- ({\y},0) node[below] {$y$}; % Optional: Add axis labels \draw (-.2,2.5) node[left] {$f_Y(u)$}; \draw (3,-.5) node[below] {$u$}; % Optional: Add axes \draw[->] (0,0) -- (6.2,0) node[right] {}; \draw[->] (0,0) -- (0,5) node[above] {}; \end{tikzpicture}  ## The Probability of $u$ Falling Between $x$ and $y$ #### INSERT INTO .TEX DOCUMENT \begin{tikzpicture} % define normal distribution function 'normaltwo' \def\normaltwo{\x,{4*1/exp(((\x-3)^2)/2)}} % input x and y parameters \def\y{4.4} \def\x{3.4} % this line calculates f(y) \def\fy{4*1/exp(((\y-3)^2)/2)} \def\fx{4*1/exp(((\x-3)^2)/2)} % Shade orange area underneath curve. \fill [fill=orange!60] ({\x},0) -- plot[domain={\x}:{\y}] (\normaltwo) -- ({\y},0) -- cycle; % Draw and label normal distribution function \draw[color=blue,domain=0:6] plot (\normaltwo) node[right] {}; % Add dashed line dropping down from normal. \draw[dashed] ({\y},{\fy}) -- ({\y},0) node[below] {$y$}; \draw[dashed] ({\x},{\fx}) -- ({\x},0) node[below] {$x$}; % Optional: Add axis labels \draw (-.2,2.5) node[left] {$f_Y(u)$}; \draw (3,-.5) node[below] {$u$}; % Optional: Add axes \draw[->] (0,0) -- (6.2,0) node[right] {}; \draw[->] (0,0) -- (0,5) node[above] {}; \end{tikzpicture}  The TikZ code snippet above is meant to be dropped into a .tex document and work without any further “tinkering”. Please let me know if this is not the case! Tags: , , June 17, 2011 ## TikZ diagrams for economists: An excise tax I have been dabbling with the TikZ package to create some diagrams relevant to a first year microeconomics course. The following diagram of an excise tax may be useful to others wishing to integrate similar diagrams into their LaTeX documents or Beamer presentations. To use, insert the following code anywhere you like within a .tex document (you must include \usepackage{tikz} in your header): This diagram was created using TikZ. #### INSERT INTO .TEX DOCUMENT % TikZ code: An excise tax \begin{tikzpicture}[domain=0:5,scale=1,thick] \usetikzlibrary{calc} %allows coordinate calculations. \usetikzlibrary{decorations.pathreplacing} %allows drawing curly braces. % Define linear parameters for supply and demand \def\dint{4.5} %Y-intercept for DEMAND. \def\dslp{-0.5} %Slope for DEMAND. \def\sint{1.2} %Y-intercept for SUPPLY. \def\sslp{0.8} %Slope for SUPPLY. \def\tax{1.5} %Excise (per-unit) tax % Define Supply and Demand Lines as equations of parameters defined above. \def\demand{\x,{\dslp*\x+\dint}} \def\supply{\x,{\sslp*\x+\sint}} \def\demandtwo{\x,{\dslp*\x+\dint+\dsh}} \def\supplytwo{\x,{\sslp*\x+\sint+\ssh}} % Define coordinates. \coordinate (ints) at ({(\sint-\dint)/(\dslp-\sslp)},{(\sint-\dint)/(\dslp-\sslp)*\sslp+\sint}); \coordinate (ep) at (0,{(\sint-\dint)/(\dslp-\sslp)*\sslp+\sint}); \coordinate (eq) at ({(\sint-\dint)/(\dslp-\sslp)},0); \coordinate (dint) at (0,{\dint}); \coordinate (sint) at (0,{\sint}); \coordinate (teq) at ({(\sint+\tax-\dint)/(\dslp-\sslp)},0); %quantity \coordinate (tep) at (0,{(\sint+\tax-\dint)/(\dslp-\sslp)*\sslp+\sint+\tax}); %price \coordinate (tint) at ({(\sint+\tax-\dint)/(\dslp-\sslp)},{(\sint+\tax-\dint)/(\dslp-\sslp)*\sslp+\sint+\tax}); %tax equilibrium \coordinate (sep) at (0,{\sslp*(\sint+\tax-\dint)/(\dslp-\sslp)+\sint}); \coordinate (sen) at ({(\sint+\tax-\dint)/(\dslp-\sslp)},{\sslp*(\sint+\tax-\dint)/(\dslp-\sslp)+\sint}); % DEMAND \draw[thick,color=blue] plot (\demand) node[right] {$P(q) = -\frac{1}{2}q+\frac{9}{2}$}; % SUPPLY \draw[thick,color=purple] plot (\supply) node[right] {Supply}; % Draw axes, and dotted equilibrium lines. \draw[->] (0,0) -- (6.2,0) node[right] {$Q$}; \draw[->] (0,0) -- (0,6.2) node[above] {$P$}; \draw[decorate,decoration={brace},thick] ($(sep)+(-0.8,0)$) -- ($(tep)+(-0.8,0)$) node[midway,below=-8pt,xshift=-18pt] {tax}; \draw[dashed] (tint) -- (teq) node[below] {$Q_T$}; \draw[dashed] (tint) -- (tep) node[left] {$P_d$}; \draw[dashed] (sen) -- (sep) node[left] {$P_s$}; \end{tikzpicture}  The TikZ code snippet above is meant to be dropped into a .tex document and work without any further “tinkering”. Please let me know if this is not the case! Tags: , , June 11, 2011 ## TikZ diagrams for economists: A price ceiling I have been dabbling with the TikZ package to create some diagrams relevant to a first year microeconomics course. The following diagram of a price ceiling may be useful to others wishing to integrate similar diagrams into their LaTeX documents or Beamer presentations. To use, insert the following code anywhere you like within a .tex document (you must include \usepackage{tikz} in your header): This diagram was created with the TikZ package in LaTeX. #### INSERT INTO .TEX DOCUMENT \begin{tikzpicture}[domain=0:5,scale=1,thick] \usetikzlibrary{calc} %allows coordinate calculations. %Define linear parameters for supply and demand \def\dint{4.5} %Y-intercept for DEMAND. \def\dslp{-0.5} %Slope for DEMAND. \def\sint{1.2} %Y-intercept for SUPPLY. \def\sslp{0.8} %Slope for SUPPLY. \def\pfc{2.5} %Price floor or ceiling \def\demand{\x,{\dslp*\x+\dint}} \def\supply{\x,{\sslp*\x+\sint}} % Define coordinates. \coordinate (ints) at ({(\sint-\dint)/(\dslp-\sslp)},{(\sint-\dint)/(\dslp-\sslp)*\sslp+\sint}); \coordinate (ep) at (0,{(\sint-\dint)/(\dslp-\sslp)*\sslp+\sint}); \coordinate (eq) at ({(\sint-\dint)/(\dslp-\sslp)},0); \coordinate (dint) at (0,{\dint}); \coordinate (sint) at (0,{\sint}); \coordinate (pfq) at ({(\pfc-\dint)/(\dslp)},0); \coordinate (pfp) at ({(\pfc-\dint)/(\dslp)},{\pfc}); \coordinate (sfq) at ({(\pfc-\sint)/(\sslp)},0); \coordinate (sfp) at ({(\pfc-\sint)/(\sslp)},{\pfc}); % DEMAND \draw[thick,color=blue] plot (\demand) node[right] {$P(q) = -\frac{1}{2}q+\frac{9}{2}$}; % SUPPLY \draw[thick,color=purple] plot (\supply) node[right] {Supply}; % Draw axes, and dotted equilibrium lines. \draw[->] (0,0) -- (6.2,0) node[right] {$Q$}; \draw[->] (0,0) -- (0,6.2) node[above] {$P$}; %Price floor and ceiling lines \draw[dashed,color=black] plot (\x,{\pfc}) node[right] {$P_c$}; \draw[dashed] (pfp) -- (pfq) node[below] {$Q_d$}; \draw[dashed] (sfp) -- (sfq) node[below] {$Q_s$}; \draw[->,baseline=5] ($(0,{\pfc})+(-1.5,0.7)$) node[label= left:Price Ceiling] {} -- ($(0,{\pfc})+(-.1,0.1)\$);

\end{tikzpicture}

Tags: , ,