% !TEX TS-program = knitr % \VignetteIndexEntry{The tikzDevice Package} % \VignetteDepends{tikzDevice} % \VignetteEngine{knitr::knitr} \documentclass[10pt,oneside,letterpaper,article]{memoir} \usepackage[utf8]{inputenc} \usepackage{tikzDeviceVignette} <>= library(tikzDevice) if( !file.exists('figs') ){dir.create( 'figs' )} options(tikzMetricsDictionary='.tikzMetrics') knitr::opts_chunk$set( echo=FALSE, fig.path='figs/fig', message=FALSE, width = 100, comment = NA ) knitr::knit_hooks$set( source = function(x, options) { paste("\\vspace{-1ex}", "\\begin{tikzCodeBlock}[listing style=sweavechunk]", paste(x, collapse = '\n'), "\\end{tikzCodeBlock}\n\n", sep = '\n') }, output = function(x, options) { paste("\\vspace{-2ex}", "\\begin{Verbatim}[frame=single]", sub("\n+$", "", paste(x, collapse = '\n')), "\\end{Verbatim}", "", sep = '\n') }, warning = function(x, options) { paste("\\vspace{-2ex}", "\\begin{Verbatim}[frame=single,formatcom=\\color{warningcolor}]", sub("\n+$", "", paste(strwrap(x, width = options$width), collapse = '\n')), "\\end{Verbatim}", "", sep = '\n') }, chunk = function(x, options) x ) @ \title{TikZDevice: LaTeX Graphics for R} \author{Charlie Sharpsteen and Cameron Bracken} \date{\Sexpr{strftime(read.dcf(system.file('DESCRIPTION', package = 'tikzDevice'), fields = 'Date'), format = '%B %d, %Y')}} \gdef\packageURL{\url{https://github.com/yihui/tikzDevice}} \gdef\packageVersion{\Sexpr{tikzDevice:::getTikzDeviceVersion()}} % Use the hyperref package to fill in PDF metadata. \hypersetup{ pdftitle=\thetitle, pdfauthor=\theauthor, pdfsubject={Manual for Version: \packageVersion, \thedate} } \begin{document} % ----------------------------------------------------------------------------- % Cover Page % ----------------------------------------------------------------------------- <>= tikz('figs/titlePlot.tex',width=4,height=4) x <- seq(-4.5,4.5,length.out=100) y <- dnorm(x) xi <- seq(-2,2,length.out=30) yi <- dnorm(xi) plot(x,y,type='l',col='blue',ylab='$p(x)$',xlab='$x$') lines(xi,yi,type='s') lines(range(xi),c(0,0)) lines(xi,yi,type='h') title(main="$p(x)=\\frac{1}{\\sqrt{2\\pi}}e^{-\\frac{x^2}{2}}$") int <- integrate(dnorm,min(xi),max(xi),subdivisions=length(xi)) text(2.8,0.3,paste( "\\small$\\displaystyle\\int_{",min(xi),"}^{",max(xi),"}p(x)dx", "\\approx",round(int[['value']],3),'$',sep='')) dev.off() @ \begin{titlingpage} % NOTE: % Most dimensions and positions in this cover page were optimized for US % Letter stock size and so are given in inches. It may be useful to revise % this one day so that the layout is a bit more scalable. % % Use remember picture and overlay so that `current page` coordinates can be % accessed. \begin{tikzpicture}[remember picture, overlay] % Title and Info % -------------- {\fontsize{60}{36} \node[below right = 0.5em of current page.north west, anchor = north east, rotate = 90, outer sep = 0pt, inner sep = 0pt ] (title) {\bfseries{\fontsize{36}{36}\selectfont\color{red}\TikZ}Device}; } \draw[line width = 5pt] ([xshift = 7.5pt]title.base west) -- ([xshift = 7.5pt]title.base east); % Have to split subtitle, authors, etc. into several nodes because % apparently TikZ can't deal with font change commands and line breaks % existing in the same node. A bit of a pain because the value of % \baselineskip has to be twaddled by wrapping some \nodes in font % size descriptors. \node[right = 12.5pt of title.base east, anchor = north west, align = left, font = {\Huge\bfseries} ] (subtitle) {\LaTeX\ Graphics for \lang{R}}; {\huge \node[below = \baselineskip of subtitle.base west, anchor = north west, align = left, font = {\LARGE} ] (authors) {% Charlie Sharpsteen\\ Cameron Bracken% }; } \node[right = 12.5pt of title.base west, anchor = base west, align = left ] (packageInfo) {% \thedate\\ \packageURL% }; {\LARGE \node[above = \baselineskip of packageInfo.north west, anchor = base west, align = left, font = {\LARGE\bfseries} ] (version) {Version: \packageVersion}; } % Logo and Plot % ------------- % Scaling the R logo to a width of 4.75 in was determed through trial and % error. The center of the image is shifted relative to the bottom right % corner of the page such that the point where the right leg of the "R" % glyph intersects the inside of the halo is sitting over the corner of the % page. \node[inner sep = 0pt, above left = 0.78in and 1.48in of current page.south east, anchor = center ] (Rlogo) {\includegraphics[width=4.75in]{img/Rlogo}}; % This node contains an embedded `tikzpicture` environment produced by the % tikzTitlePlot code block. \node[anchor = north east, inner sep = 0pt ] (titlePlot) at (current page.north east) {\input{figs/titlePlot.tex}}; % Connect Logo and Plot % --------------------- \node[below left = 0.325\stockheight and 0.325\stockwidth of current page.center] (midPointA) {}; \node[below right = 0.125\stockheight and 0.125\stockwidth of current page.center] (midPointB) {}; \tikzset{ grow bigger/.style={decoration = { shape backgrounds, shape = dart, shape scaled, shape start size = 0.125cm, shape end size = 0.5cm, shape sep = {.25cm, between borders} }} } \path[decorate, grow bigger, fill = black!25] plot[smooth, tension = 1] coordinates{(Rlogo.190) (midPointA) (midPointB) (titlePlot.south)}; \end{tikzpicture} \end{titlingpage} % ----------------------------------------------------------------------------- % Table of Contents % ----------------------------------------------------------------------------- \frontmatter \tableofcontents* \mainmatter % ----------------------------------------------------------------------------- % Chapter 1: Introduction % ----------------------------------------------------------------------------- \chapter{Introduction} The \pkg{tikzDevice} package provides a graphics output device for \lang{R} that records plots in a \LaTeX -friendly format. The device transforms plotting commands issued by \lang{R} functions into \LaTeX\ code blocks. When included in a paper typeset by \LaTeX , these blocks are interpreted with the help of TikZ---a graphics package for \TeX\ and friends written by Till Tantau. By allowing \LaTeX\ to handle typesetting of text in \lang{R} plots along with the rest of the text in the paper the full power of \TeX\ is available to the \lang{R} user. There are also no discontinuities in font selection and typesetting as demonstrated by a comparison between \autoref{fig:pdf-example} and \autoref{fig:tikz-example}. % FIXME: % This example is biased. It would be best to choose a TeX font for which AFM % metrics are available and show how much of a pain in the ass it is to use the % R `Type1Font` function vs. how easy it is to set tikzDevice options and let % TeX do the heavy lifting. \begin{figure}[!hb] \centering \begin{minipage}[t]{0.4\linewidth} \begin{tikzCodeBlock}[listing style=sweavechunk, code body/.append style={codebody color=white}] pdf('pdf-example.pdf', width = 3.25, height = 3.25) plot(1, 1, main = 'Hello!') dev.off() \end{tikzCodeBlock} <>= pdf('figs/pdf-example.pdf', width = 3.25, height = 3.25) plot(1, 1, main = 'Hello!', ps = 10) dev.off() @ \includegraphics{figs/pdf-example} \caption{Output from \code{pdf()}} \label{fig:pdf-example} \end{minipage} \hspace{0.1\linewidth} \begin{minipage}[t]{0.4\linewidth} \begin{tikzCodeBlock}[listing style=sweavechunk, code body/.append style={codebody color=white}] tikz('tikz-example.tex', width = 3.25, height = 3.25) plot(1, 1, main = 'Hello \\TeX !') dev.off() \end{tikzCodeBlock} <>= tikz('figs/tikz-example.tex', width = 3.25, height = 3.25) plot(1, 1, main = 'Hello \\TeX !') dev.off() @ \input{figs/tikz-example.tex} \caption{Output from \code{tikz()}} \label{fig:tikz-example} \end{minipage} \end{figure} This document is divided into three parts. \autoref{part:usage} describes the package functionality and provides example usage. Besides the \lang{R} environment, use of the \TikZ\ device requires the user to have a working \LaTeX{} compiler along with an installed version of the \TikZ{} package---version 2.00 or greater. \autoref{part:installation} of this documentation offers suggestions on how to get these dependencies installed and working properly. \autoref{part:implementation} is intended for those who are curious as to the details of how this package is implemented. This part attempts to explain how the \pkg{tikzDevice} package does the things that it does and why it chooses to do them that way. The authors have attempted to write this part of the documentation in a way that is accessible to users as well as developers. This information is provided in the hope that the \pkg{tikzDevice} may serve as a case study for creating new \lang{R} graphics devices. This part of the documentation may also help those considering undertaking the transition from casual package-building to full-on hacking of the \lang{R} internals. \section{Acknowledgements} This package would not have been possible without the hard work and ingenuity of many individuals. This package straddles the divide between two great open source communities---the \lang{R} programming language and the \TeX{} typesetting system. It is our hope that this work will make it easier for users to leverage the strengths of both systems. First off, we would like to thank the \lang{R} Core Team for creating such a wonderful, open and flexible programming environment. Compared to other languages we have used, creating packages and extensions for \lang{R} has always been a liberating experience. This package started as a fork of the Pic\TeX\ device created by Valerio Aimale which is part of the \lang{R} core graphics system. Without access to this simple, compact example of implementing a graphics device we likely would have abandoned the project in its infancy. We would also like to thank Paul Murrell for all of his work on the \lang{R} graphics system and especially for his research and documentation concerning the differences between the font systems used by \TeX{} and \lang{R}. This package also owes its existence to Friedrich Leisch's work on the \pkg{Sweave} system and Roger D. Peng's \pkg{cacheSweave} extension. These two tools got us interested in the concept of Literate Programming and development of this package was driven by our desire to achieve a more seamless union between our reports and our code. The performance of this package is also enhanced by the database capabilities provided by Roger D. Peng's \pkg{filehash} package. Without this package, the approach to calculating font metrics taken by the \pkg{tikzDevice} would be infeasible. Last, but certainly not least, we would like to thank Till Tantau, Mark Wibrow and the rest of the PGF/\TikZ\ team for creating the \LaTeX\ graphics package that makes the output of this device meaningful. We would also like to express deep appreciation for the beautiful documentation that has been created for the \TikZ\ system. As always, there are many more who have contributed in ways too numerous to list.\\[\baselineskip] \noindent Thank you!\\ \quad{\itshape ---The tikzDevice Team} \nocite{murrellTex} \nocite{rintern2009} \nocite{tantau2008} \nocite{peng2006} \partimage{ \node[above left = 1in of current page.south east, anchor = south east, scale = 1.25 ] % This image is generated by an example in chapter 3. {\input{figs/latexEx}}; } \part{Usage and Examples} \label{part:usage} % ----------------------------------------------------------------------------- % Chapter 2: Package Loading % ----------------------------------------------------------------------------- \chapter{Loading the Package} The functions in the \pkg{tikzDevice} package are made accessible in the \lang{R} environment by using \code{library()}: \begin{Verbatim}[frame=single] library(tikzDevice) \end{Verbatim} \noindent Upon loading, the package will search for the following \LaTeX\ compilers: \begin{itemize} \item{\hologo{pdfLaTeX}} \item{\hologo{XeLaTeX}} \item{\hologo{LuaLaTeX}} \end{itemize} Access to \LaTeX\ is essential for the device to produce output as the compiler is queried for font metrics when constructing plots that contain text. For more information on why communication between the device and \LaTeX\ is necessary, see \autoref{part:implementation}. The package will fail to load if \hologo{pdfLaTeX} cannot be located. The presence of the \hologo{XeLaTeX} and \hologo{LuaLaTeX} compilers is optional. When the package loads successfully, a startup message will be printed that looks similar to the following: \begin{Verbatim}[frame=single] Loading required package: filehash filehash: Simple key-value database (2.2 2011-07-21) tikzDevice: R Graphics Output in LaTeX Format (v0.7) LaTeX found in the PATH using the command: pdflatex XeLaTeX found in the PATH using the command: xelatex LuaLaTeX found in the PATH using the command: lualatex \end{Verbatim} If a working \hologo{pdfLaTeX} compiler cannot be found, the \pkg{tikzDevice} package will fail to load and a warning message will be displayed: \begin{Verbatim}[frame=single] Error : .onLoad failed in loadNamespace() for 'tikzDevice', details: call: fun(libname, pkgname) error: An appropriate LaTeX compiler could not be found. Access to LaTeX is required in order for the TikZ device to produce output. The following places were tested for a valid LaTeX compiler: the global option: tikzLatex the environment variable: R_LATEXCMD the environment variable: R_PDFLATEXCMD the global option: latexcmd the PATH using the command: pdflatex the PATH using the command: latex the PATH using the command: /usr/texbin/pdflatex ... Error: loading failed \end{Verbatim} In this case, \pkg{tikzDevice} has done its very best to locate a working compiler and came up empty. If you have a working \LaTeX\ compiler, the next section describes how to inform the \pkg{tikzDevice} package of its location. For suggestions on how to obtain a \LaTeX\ compiler, see \autoref{part:installation}. \section{Options That Affect Package Behavior} \label{sec:options} The \pkg{tikzDevice} package is influenced by a number of options that may be set locally in your \lang{R} scripts or in the \lang{R} console or globally in a \code{.Rprofile} file. All of the options can be set by using \code{options(