This repository has been archived by the owner on Sep 23, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 36
/
tikzDevice.Rnw
1710 lines (1197 loc) · 87.9 KB
/
tikzDevice.Rnw
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
% !TEX TS-program = Sweave
\documentclass{article}
% \VignetteIndexEntry{The tikzDevice Package}
% \VignetteDepends{tikzDevice}
% \usepackage{Sweave}
\usepackage[T1]{fontenc}
\usepackage{lmodern}
\usepackage[scaled=.85]{inconsolata}
\usepackage[colorlinks]{hyperref}
% Extra text effects (strikethrough)
\usepackage{ulem}
% Various TeX logos---included in the Oberdiek bundle which contains hyperref,
% so there is a good chance it will be installed.
\usepackage{hologo}
% Sexyness
\usepackage{tikz}
\usetikzlibrary{calc,positioning}
\usetikzlibrary{shapes.multipart,shapes.geometric,shapes.symbols,shapes.arrows}
\usetikzlibrary{decorations.shapes,decorations.text,decorations.pathreplacing}
% Page layout
\usepackage[parfill]{parskip}
\usepackage[letterpaper,margin=1in]{geometry}
\usepackage{epigraph}
\usepackage{multicol}
\usepackage{pdflscape}
% Graphics control.
\usepackage{graphicx}
\usepackage{float}
% Bibliography
\usepackage{natbib}
\bibliographystyle{agufull04}
\usepackage[nogin,noae]{Sweave}
% Extra pretty pretty printing.
\usepackage{tikzCodeBlock}
\usepackage{sweavetolst}
% Macros created for this document. Make sure tikzCodeBlock is loaded first.
% For now.
\input{tikzDeviceMacros}
<<setup,echo=F,results=hide>>=
if( !file.exists( 'figs' ) ) dir.create( 'figs' )
require(tikzDevice)
options(prompt = ' ', continue = ' ')
@
\title{The \pkg{tikzDevice} Package\\
{\large\url{http://r-forge.r-project.org/projects/tikzdevice}}
}
\author{Charlie Sharpsteen and Cameron Bracken}
\date{Version
\Sexpr{tikzDevice:::getTikzDeviceVersion()}-{\bfseries\color{red}Beta}\qquad November, 2011}
\begin{document}
\SweaveOpts{echo=F,prefix.string=figs/fig}
%---------------------------- Cover Page -----------------------------------------------------------
\thispagestyle{empty}
% A more complex title page
% HAH! God bless the pgf manual- I've been trying to solve this for
% ever- \vfill has no effect unless you bracket your contents in empty
% \vboxes.
\vbox{}
\vspace{0.5\textheight}
\begin{tikzpicture}[remember picture,overlay]
\node[anchor=west,scale=2, inner sep=0pt, outer sep=0pt] (title) at (-1cm,0)
{\LARGE\bfseries{\color{red}\TikZ}\thinspace\Huge Device};
\draw[line width=5pt] ([yshift=-5pt]title.base west) -- ([yshift=-5pt]title.base east);
\coordinate (titleOut) at ($(title.north east) + (24pt,0pt)$);
\coordinate (titleIn) at ($(title.base west) - (6pt,24pt)$);
\node[color=black!80,below=24pt of title.base east,anchor=east] (sub)
{\bfseries\itshape\Large \LaTeX{} Graphics for R};
\end{tikzpicture}
\vfill
\vbox{}
\begin{tikzpicture}[remember picture,overlay,>=stealth]
\node (R) at ($(current page.south west) + (18cm,2cm)$)
{\scalebox{0.85}{\includegraphics[width=0.8\textwidth]{img/Rlogo}}};
\tikzset{
bigger/.style={decoration={shape start size=.125cm, shape end size=.5cm}},
decoration={shape backgrounds,
shape sep={.25cm, between borders},shape scaled,shape=circle}
}
\fill[decorate,bigger, blue!25] (R) to[out=190,in=240] (titleIn);
\end{tikzpicture}
\begin{tikzpicture}[overlay,remember picture]
% Low-level PGF voodoo
% Something is seriously borked with current page.north east,
% it's not where you would expect it to be :P
\newdimen\overlayXoff
\newdimen\overlayYoff
\pgfextracty{\overlayXoff}{\pgfpointanchor{current page}{north east}}
\pgfextracty{\overlayYoff}{\pgfpointanchor{current page}{north east}}
\pgfmathparse{\overlayYoff - 4.5in}
\overlayYoff = \pgfmathresult pt
\pgfmathparse{\overlayXoff - 7in}
\overlayXoff = \pgfmathresult pt
\begin{scope}[x=1pt,y=1pt,yshift=\overlayYoff,xshift=\overlayXoff]
<<tikzTitlePlot,results=hide>>=
tikz('figs/titlePlot.tex',bareBones=T,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()
@
\input{figs/titlePlot.tex}
\coordinate (plotIn) at (2in,0.5in);
\end{scope}
\tikzset{
bigger/.style={decoration={shape start size=.125cm, shape end size=.5cm}},
decoration={shape backgrounds,
shape sep={.25cm, between borders},shape scaled,shape=dart}
}
\fill[decorate,thick,bigger,color=black!25]
(titleOut) to[out=20,in=260] (plotIn);
\end{tikzpicture}
\newpage
%---------------------------- Table of Contents -----------------------------------------------------------
\pagenumbering{roman}
\maketitle
\tableofcontents
\newpage
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Documentation starts here.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\pagenumbering{arabic}
% A friendly reminder that this package is currently unstable.
\tikzDocDisclaim{Caveat Utilitor}
{
This is a friendly reminder that the \pkg{tikzDevice} package is currently considered by its designers to be a {\bfseries beta work}. The package will remain in Beta until the 1.0 release to allow the authors to consider design decisions underlying the package. {\bfseries This means the authors are currently reserving the right to alter the package interface in ways that may break existing code that uses the package.} Two open issues that may necessitate such a change are:
\vskip\baselineskip
\begin{itemize}
\item{Handling of characters encoded using UTF8}
\item{Compatibility with multiple \TeX\ dialects such as Con\TeX t or plain \TeX .}
\end{itemize}
\vskip\baselineskip
The stability of the package interface is a priority to us but currently we are allowing other concerns to outrank it. When we commit to maintaining a given package structure, the beta flag will be removed and consistency of interface will become a top priority. \\[1em]
Thanks for giving our package a try!\\
\quad{\itshape --The tikzDevice Team}
}
\section{Introduction}
The \pkg{tikzDevice} package allows for R graphics output in a native \LaTeX{} format. That is, the \code{tikz()} function produces plain-text files that can be interpreted using \TikZ, a package for \LaTeX. These files can be directly included in \LaTeX{} documents by way of the \verb'\input{}' statement. Allowing \LaTeX{} to handle both typesetting and figure composition bestows the resulting document with a clean, unified look as there are no discontinuities in the size and selection of fonts used in the text and those used in the figures.
This document is divided into three parts. The first part describes the functions that the package makes available to the \lang{R} user and provides examples of their capabilities. Besides the \lang{R} environment, use of the \TikZ{} device device requires the user to have a working \LaTeX{} compiler along with an installed version of the \TikZ{} package-- version 2.00 or greater. The second part of this documentation offers suggestions on how to get these tools working properly.
The third part of the documentation is intended for those who are curious as to the details of how this package has been implemented. It attempts to explain how the \TikZ{} 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 has been done in the hope that this project may serve as a case study in creating an \lang{R} graphics device. 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 to leverage the strengths of both systems.
First off, we would like to thank the 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. Without access to such a concise, compact example of implementing a \lang{R} graphics device we likely would have abandoned the project in it's infancy. We would also like to thank Paul Murrel 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 it's existence to Friedrich Leisch's work on the \code{Sweave} system and Roger D. Peng's \code{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 \code{filehash} package. Without this package, the approach to calculating font metrics taken by the \code{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 excellent documentation that has been created for the \TikZ{} system.
As always, there are many more who have contributed in ways too numerous to list.
Thank you!\\
\vbox{}{\quad\itshape --The tikzDevice Team}
\nocite{murrellTex}
\nocite{rintern2009}
\nocite{tantau2008}
\nocite{peng2006}
\part{Usage and Examples}
\label{part:one}
%---------------------------- Package Loading -----------------------------------------------------------
\section{Loading the Package}
The functions in the \pkg{tikzDevice} package are made accessible in the \lang{R} environment by using either the \code{library()} or \code{require()} functions like so:
\begin{Verbatim}[frame=single]
require(tikzDevice)
\end{Verbatim}
Upon loading, the package will search for a usable \LaTeX{} compiler. Access to \LaTeX{} is essential for the device to produce correct output as the compiler is queried for font metrics several times during device output. For more information on why communication between the device and \LaTeX{} is necessary, see \autoref{part:three}. If the search for a compiler is successful the package startup message should look similar to the following:
\begin{Verbatim}[frame=single]
filehash: Simple key-value database (2.0-1 2008-12-19)
tikzDevice: A Device for R Graphics Output in PGF/TikZ Format (v0.3.5)
Checking for a LaTeX compiler...
pdfTeX 3.1415926-1.40.9-2.2 (Web2C 7.5.7)
kpathsea version 3.5.7
...
A working LaTeX compiler was found in:
The R environment variable R_LATEXCMD
Global option tikzLatex set to:
/usr/texbin/latex
\end{Verbatim}
If a working \LaTeX{} compiler cannot be found, the \pkg{tikzDevice} package will fail to load and a warning message will be displayed:
\begin{Verbatim}[frame=single]
An appropriate LaTeX compiler could not be found.
Access to LaTeX is currently required in order for the
TikZ device to produce output.
The following places were tested for a valid LaTeX compiler:
A pre-existing value of the global option tikzLatex
The R environment variable R_LATEXCMD
The R environment variable R_PDFLATEXCMD
The global option latexcmd
The PATH using the command latex
The PATH using the command pdflatex
...
Error : .onLoad failed in 'loadNamespace' for 'tikzDevice'
Error: package/namespace load failed for 'tikzDevice'
\end{Verbatim}
In this case, \pkg{tikzDevice} has done it's 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:two}.
\subsection{\lang{R} 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(<option> = <value>)}. These options allow for the use of custom \code{documentclass} declarations, \LaTeX{} packages, and typesetting engines (e.g. XeLaTeX). The defaults , if are any for a given option, are shown below the description. The global options are:
\begin{description}
% The additional indent added by the description will be picked up by the listings
% package and inserted into the code blocks. It is hard to detect in general when this
% happens- so we'll just temporarily shift the listing margin and shorten the max
% width of tikzCodeBlock node bodies. Since this is all done inside the description
% environment, the changes will disappear when the environment ends.
\lstset{xleftmargin=-\leftmargini}
\newlength\tikzShortenLine
\setlength\tikzShortenLine{\textwidth}
\addtolength\tikzShortenLine{-\leftmargini}
\tikzset{/tikzCode/defaults/code body/.append style={text width=\tikzShortenLine}}
\item[\code{tikzDefaultEngine}] {
Specifies which typesetting engine functions in the \pkg{tikzDevice}
package will prefer. Current possible values are \hologo{pdfTeX} or
\hologo{XeTeX} which will respectively trigger the use of the
\hologo{pdfLaTeX} and \hologo{XeLaTeX} compilers.
\begin{tikzCodeBlock}[title={Choosing the \TeX\ engine},listing style=sweavechunk]
options(tikzDefaultEngine = 'pdftex')
# Or..
options(tikzDefaultEngine = 'xetex')
\end{tikzCodeBlock}
}
\item[\code{tikzLatex} and \code{tikzXelatex}] {
Specifies the location of the \LaTeX{} and \hologo{XeLaTeX} compilers to be
used by \pkg{tikzDevice}. Setting a default for this this option may help
the package locate a missing compiler:
\begin{tikzCodeBlock}[title={Setting default compilers in \code{.Rprofile}},listing style=sweavechunk]
options(tikzLatex = '/path/to/latex/compiler')
options(tikzXelatex = '/path/to/xelatex/compiler')
\end{tikzCodeBlock}
}
\item[\code{tikzMetricsDictionary}]{ When using the graphics device provided by \pkg{tikzDevice}, you may notice that \lang{R} appears to ``lag" or ``hang" when commands such as \code{plot()} are executed. This is because the device must query the \LaTeX{} compiler for string widths and font metrics. For a normal plot, this may happen dozens or hundreds of times- hence \lang{R} becomes unresponsive for a while. The good news is that the \code{tikz()} code is designed to cache the results of these computations so they need only be performed once for each string or character. By default, these values are stored in a temporary cache file which is deleted when \lang{R} is shut down. A location for a permanent cache file may be specified:
\begin{tikzCodeBlock}[title={Setting a location in \code{.Rprofile} for a permanent metrics dictionary},listing style=sweavechunk]
options( tikzMetricsDictionary = '/path/to/dictionary/location' )
\end{tikzCodeBlock}
}
\item[\code{tikzDocumentDeclaration}]{A string. The documentclass declaration when \code{standAlone == TRUE} as well as when font metrics are calculated}
\begin{tikzCodeBlock}[title={Default},listing style=sweavechunk]
options( tikzDocumentDeclaration = "\\documentclass{article}" )
\end{tikzCodeBlock}
\item[\code{tikzFooter}]{A character vector. The footer to be used only when \code{standAlone==TRUE} }
\begin{tikzCodeBlock}[title={Default},listing style=sweavechunk]
options( tikzFooter = c( "\\end{document}" ) )
\end{tikzCodeBlock}
\item[\code{tikzLatexPackages} and \code{tikzXelatexPackages}]{
Character vectors. These are the packages which are included when using the
\code{standAlone} option as well as when font metrics are calculated. If you
use additional packages that affect fonts, such as mathpazo which provides a
Palatino-style font, these packages should be added to this list.
\begin{tikzCodeBlock}[title={Default},listing style=sweavechunk]
options( tikzLatexPackages = c(
"\\usepackage{tikz}",
"\\usepackage[active,tightpage]{preview}",
"\\PreviewEnvironment{pgfpicture}",
"\\setlength\\PreviewBorder{0pt}")
)
\end{tikzCodeBlock}
\begin{tikzCodeBlock}[title={Adding a package that affects fonts},listing style=sweavechunk]
options( tikzLatexPackages = c(
getOption( "tikzLatexPackages" ),
"\\usepackage{mathpazo}"
))
\end{tikzCodeBlock}
}
\item[\code{tikzMetricPackages} and \code{tikzUnicodeMetricPackages}] {
Character vectors. These are the extra packages which are additionally
loaded when doing font metric calculations. As you see below, the font
encoding is set to Type 1. This is very important so that character codes
of \LaTeX{} and \lang{R} match up. The Unicode metric packages are used
when a \hologo{XeTeX} engine is in use.
\begin{tikzCodeBlock}[title={Default},listing style=sweavechunk]
options( tikzMetricPackages = c(
"\\usepackage[utf8]{inputenc}",
"\\usepackage[T1]{fontenc}",
"\\usetikzlibrary{calc}")
)
\end{tikzCodeBlock}
}
\item[\code{tikzSanitizeCharacters}]{A character vector of special latex characters to replace. These values should correspond to the replacement values from the \code{tikzReplacementCharacters} option.}
\begin{tikzCodeBlock}[title={Default},listing style=sweavechunk]
options( tikzSanitizeCharacters = c('%','$','}','{','^') )
\end{tikzCodeBlock}
\item[\code{tikzReplacementCharacters}]{A character vector of replacements for special latex characters. These values should correspond to the values from the \code{tikzSanitizeCharacters} option.}
\begin{tikzCodeBlock}[title={Default},listing style=sweavechunk]
options( tikzReplacementCharacters = c('\\%','\\$','\\','\\','\\^'))
\end{tikzCodeBlock}
\item[\code{tikzRasterResolution}] {
When \code{tikz} is requested to add a raster to a graphic, the
raster is written to a PNG file which is then included into the LaTeX
code. This option controls the resolution (dpi) at which the PNG files
are created.
\begin{tikzCodeBlock}[title={Default},listing style=sweavechunk]
options(tikzRasterResolution = 300)
\end{tikzCodeBlock}
}
\item[\code{tikzPdftexWarnUTF}] {
A \code{TRUE/FALSE} value that controls whether warnings are printed if
Unicode characters are sent to a device using the \hologo{pdfTeX} engine.
}
\end{description}
For convenience the function \code{setTikzDefaults()} is provided which sets all the global options back to their original values.
The proper placement of a \code{.Rprofile} file is explained in \code{?Startup}. For the details of why calling the \LaTeX{} compiler is necessary, see \autoref{part:three}.
\tikzDocDisclaim{A Word of Caution About Setting Options.}
{A lot of power is given to you through these global options, and with great power comes great responsibility. For example, if you do not include the \TikZ{} package in the \code{tikzLatexPackages} option then all of the string metric calculations will fail. Or if you use a different font when compiling than you used for calculating metrics, strings may be placed incorrectly. There are innumerable ways for packages to clash in \LaTeX{} so be aware.
}
\label{cache:user}
%---------------------------- tikz() function documentation -------------------------------------------------
\section{The \code{tikz()} Function}
\subsection{Description}
The \code{tikz()} function provides most of the functionality of the \pkg{tikzDevice} package. This function is responsible for creating new \lang{R} graphics devices that translate the output of graphics functions to the \TikZ{} format. The device supports many levels of output that range from stand-alone \LaTeX{} documents that may be compiled directly to code chunks that must be incorporated into existing \LaTeX{} documents using the \verb`\include{}` function.
\subsection{Usage}
The \code{tikz()} function opens a new graphics device and may be called with the following arguments:
\begin{Verbatim}[frame=single]
tikz(file = "Rplots.tex", width = 7, height = 7,
bg="transparent", fg="black", pointsize = 10, standAlone = FALSE,
bareBones = FALSE, console = FALSE, sanitize = FALSE,
engine = getOption("tikzDefaultEngine'),
documentDeclaration = getOption("tikzDocumentDeclaration"),
packages = getOption("tikzLatexPackages"),
footer = getOption("tikzFooter"))
\end{Verbatim}
\begin{description}
\item[\code{file}]{ A character string indicating the desired path to the output file. It is recommended, but not required, that the filename end in \code{.tex}.}
\item[\code{width}]{ The width of the output figure, in {\bfseries inches}. }
\item[\code{height}]{ The height of the output figure, in {\bfseries inches}. }
\item[\code{bg}]{ The starting background color for the plot. }
\item[\code{fg}]{ The starting foreground color for the plot. }
\item[\code{pointsize}]{ Base pointsize used in the LaTeX document. This option is only referenced if a valid pointsize cannot be extracted from the value of \code{getOption("tikzDocumentDeclaration")}. See \autoref{subsec:fontCalc} for more details.}
\item[\code{standAlone}]{ A logical value indicating whether the resulting file should be suitable for direct processing by \LaTeX .}
\item[\code{bareBones}]{ A logical value indicating whether the resulting \TikZ{} code produced without being placed within a \LaTeX{} \code{tikzpicture} environment.}
\item[\code{console}]{Should the output of \code{tikz} be directed to the \lang{R} console (default FALSE). This is useful for dumping tikz output directly into a \LaTeX{} document via sink. If \code{TRUE}, the file argument is ignored. Setting \code{file=''} is equivalent to setting \code{console=TRUE}.}
\item[\code{sanitize}]{Should special latex characters be replaced (Default \code{FALSE}). See the section ``Options That Affect Package Behavior'' for which characters are replaced.}
\item[\code{engine}] {
A string specifying which TeX engine to use. Possible values are 'pdftex' and
'xetex'.
}
\item[\code{documentDeclaration}]{See Section \ref{sec:options}, ``Options That Affect Package Behavior.''}
\item[\code{packages}]{See Section \ref{sec:options}, ``Options That Affect Package Behavior.''}
\item[\code{footer}]{See Section \ref{sec:options}, ``Options That Affect Package Behavior.''}
\end{description}
The first five options should be familiar to anyone who has used the default
graphics devices shipped with \lang{R}. The options \code{file}, \code{width},
\code{height}, \code{bg} and \code{fg} represent the standard graphics
parameters currently implemented by \pkg{tikzDevice}. The last two options,
\code{standAlone} and \code{bareBones}, are specific to the \code{tikz()}
graphics device and affect the structure the output file. Using these options
\code{tikz()} supports three modes of output:
\begin{itemize}
\item{Graphics production as complete \LaTeX{} files suitable for compilation.}
\item{Graphics production as complete figures suitable for inclusion in \LaTeX{} files.}
\item{Graphics production as raw figure code suitable for inclusion in an enclosing \code{tikzpicture} environment in a \LaTeX{} file.}
\end{itemize}
\subsection{Font Size Calculations}
\label{subsec:fontCalc}
The overarching goal of the `tikzDevice' is to provide seamless integration
between text in R graphics and the text of LaTeX documents that contain those
graphics. In order to achieve this integration the device must translate font
sizes specified in R to corresponding font sizes in LaTeX. The issue is that
font sizes in LaTeX are controlled by a ``base font size'' that is specified at
the beginning of the document- typically 10pt. There is no easy way in LaTeX
to change the font size to a new numerical value, such as 16pt for a plot
title. Fortunately, the TikZ graphics system allows text to be resized using a
scaling factor. The \code{tikzDevice} calculates a scaling factor used to
approximate other font sizes using the following three inputs:
\begin{itemize}
\item{The ``base font size'' specified when the graphics device is
created.}
\item{The ``character expansion factor'' parameter, specified using the `cex'
argument to functions such as described in the documentation of the
\lang{R} function \code{par()}.}
\item{The ``font size'' parameter, specified using the `ps' argument to
functions such as \code{par()} or the `fontsize' argument to functions such
as \code{gpar()}.}
\end{itemize}
The calculation used is:
\[
\mbox{Scaling Factor} = \mbox{cex} \cdot \frac{\mbox{ps}}{\mbox{base font size}}
\]
The tricky bit is the specification of the ``base font size''. By default the tikzDevice will attempt to determine this parameter by scanning the value of \code{options( "tikzDocumentDeclaration" )} using the regular expression \code{\textbackslash d+[pt]}. With the default header:
\quad\code{\textbackslash documentclass[10pt]{article}}
This regular expression will return 10 as the base pointsize to be used by the device. If the regular expression fails to produce a match, the value of the \code{pointsize} argument to the \code{tikz()} function will be used.
\subsection{UTF-8 Output}
Version 0.6.0 introduced support for (multibyte) Unicode characters in the text
of graphics. There are a few important implications/limitations of this
feature:
\begin{description}
\item[System Requirements:]
A working version of \hologo{XeLaTeX} along with the packages \code{fontspec}
and \code{xunicode} are required for direct processing of Unicode input. If
\code{tikzDevice} cannot find \hologo{XeLaTeX} then Unicode support cannot be
guaranteed.
\item[Encoding:] \code{tikzDevice} will try its best to convert characters from
other encodings but do not count on it converting things correctly, best to
do the conversion yourself beforehand to avoid unexpected output.
\item[Fonts:] Having a Unicode character actually show up in your \LaTeX{}
document relies on the font you use having the glyph available. We leave it
up to the user to know for themselves what is available. Otherwise you will
likely just get no output in place of where the character should be.
\item[plotmath:] There is specifically no support for input of plotmath
characters as unicode since the user can simply input \LaTeX{} math directly.
We strongly encourage the use of \LaTeX{} math over plotmath for style and
consistency's sake. A consequence of this is that most of the \lang{R}
examples and demos of plotmath won't work without significant manipulation
(your milage may vary but you may get anything from errors to warnings to
documents that mysteriously won't compile). That is not to say that the
output could not be duplicated with \code{tikzDevice} but the examples will
not work out of the box.
\item[Compiling:]
A graphic that contains UTF-8 characters should be compiled with
\hologo{XeLaTeX} (or possibly \hologo{LuaLaTeX}) with the \code{xunicode} and
\code{fontspec} packages enabled.
\item[ASCII only:]
Everything should be exactly the same as previous versions if only ASCII
(single byte) characters are used (i.e. character codes less than 132).
\end{description}
\subsection{Examples}
% We will shift into the figs directory here so that we don't have
% to have separate Sweave code chunks with the 'figs/' path in
% them.
<<pathStepIn,results=hide>>=
setwd('figs')
@
\subsubsection{Default Mode}
The most common use of the \code{tikz()} function is to produce a plot that will be included in another \LaTeX{} document, such as a report. Running the following example in \lang{R} will produce a very simple graphic using the \code{plot()} function.
<<simpleEx,echo=T,results=hide>>=
require(tikzDevice)
tikz('simpleEx.tex',width=3.5,height=3.5)
plot(1,main='Hello World!')
dev.off()
@
A simple \LaTeX{} document is then required to display the output of the basic \code{tikz()} command. This document must include the \TikZ{} as one of the packages that it loads. The \TikZ{} package provides several optional libraries that provide additional functionality, however none of these libraries are currently required to use the output of \code{tikz()}. Inside the \LaTeX{} document, the contents of the file \code{simpleEx.tex} are imported using the \verb`\include{}` command.
\begin{figure}[H]
\centering
\begin{minipage}{0.5\textwidth}
\begin{tikzCodeBlock}[title={Example \LaTeX{} Document},listing style=latexsource,code body/.append style={codebody color=white},no break=true]
\documentclass{article}
% All LaTeX documents including
% tikz() output must use this
% package!
\usepackage{tikz}
\begin{document}
\begin{figure}[!h]
\centering
% The output from tikz()
% is imported here.
\input{simpleEx.tex}
\caption{Simple Example}
\end{figure}
\end{document}
\end{tikzCodeBlock}
\end{minipage}
\hfill
\begin{minipage}{0.45\textwidth}
\input{figs/simpleEx.tex}
\end{minipage}
\caption{Example of simple \code{tikz()} usage.}
\end{figure}
One of the most exciting aspects of the \code{tikz()} function is that it allows the inclusion of arbitrary \LaTeX{} code in plotting commands. An important issue to note is that many \LaTeX{} commands pare prefixed by the backaslash, \textbackslash, character. This character has a special meaning as an escape charcter in many computing applications, including \lang{R}. Therefore, it is necessary to place two backslashes, \textbackslash\textbackslash, in the input to \lang{R} commands in order to cause one to appear in the output. The next example demonstrates how to use \LaTeX{} commands in plot annotation.
% Disable chunk page breaking so the following code doesn't get mangled.
\makeatletter
\tikzCode@breakPagesfalse
\makeatother
\begin{figure}[H]
\centering
\begin{minipage}{0.5\textwidth}
<<latexEx,echo=T,results=hide,keep.source=T>>=
require(tikzDevice)
tikz('latexEx.tex',
width=3.5,height=3.5)
x <- rnorm(10)
y <- x + rnorm(5,sd=0.25)
model <- lm(y ~ x)
rsq <- summary( model )$r.squared
rsq <- signif(rsq,4)
plot(x,y,main='Hello \\LaTeX!')
abline(model,col='red')
mtext(paste("Linear model: $R^{2}=",
rsq,"$" ),line=0.5)
legend('bottomright', legend =
paste("$y = ",
round(coef(model)[2],3), 'x +',
round(coef(model)[1],3), '$',
sep=''), bty= 'n')
dev.off()
@
\end{minipage}
\hfill
\begin{minipage}{0.45\textwidth}
\input{figs/latexEx.tex}
\end{minipage}
\caption{A more complicated example of \code{tikz()} usage incorporating natively rendered \LaTeX{} commands.}
\end{figure}
% Reinstate tikzCodeBlock defaults.
\makeatletter
\tikzCode@breakPagestrue
\makeatother
\subsubsection{\code{bareBones} Mode}
\code{barBones} output is designed to facilitate inclusion of code generated by
\code{tikz()} into a larger \TikZ\ graphic. Normally \code{tikz()} packages the
commands it produces as a self-contained figure. This is done by placing the
\verb`\begin{tikzpicture}` and \verb`\end{tikzpicture}` commands at the
beginning and end of the output file. When \code{bareBones} is invoked, the
\code{tikzpicture} environment is omitted which allows the output to be
embedded inside another \code{tikzpicture} of the users own construction.
<<bareBonesExample,echo=T,results=hide,keep.source=T>>=
require(tikzDevice)
require(maps)
tikz('westCoast.tex', bareBones=TRUE)
map('state', regions=c('california', 'oregon', 'washington'),
lwd=4, col='grey40')
eurekaLon <- grconvertX(-124.161, to='device')
eurekaLat <- grconvertY(40.786, to='device')
longviewLon <- grconvertX(-122.962, to='device')
longviewLat <- grconvertY(46.148, to='device')
coosLon <- grconvertX(-124.237, to='device')
coosLat <- grconvertY(43.378, to='device')
sfLon <- grconvertX(-122.419, to='device')
sfLat <- grconvertY(37.775, to='device')
tikzAnnotate(paste('\\coordinate (humBay) at (',
eurekaLon, ',', eurekaLat, ');', sep='') )
tikzAnnotate(paste('\\coordinate (longView) at (',
longviewLon, ',', longviewLat, ');', sep='') )
tikzAnnotate(paste('\\coordinate (coosBay) at (',
coosLon, ',', coosLat, ');', sep='') )
tikzAnnotate(paste('\\coordinate (sfBay) at (',
sfLon, ',', sfLat, ');', sep='') )
dev.off()
@
The \verb`\include{}` command may now be used to import the device output into
another \code{tikzpicture}. The included code must be wrapped in a \code{scope}
environment that contains the options \code{x=1pt} and \code{y=1pt}. This
informs \TikZ{} of the units being used in the coordinates of the plot output.
The options \code{xshift} and \code{yshift} may also be applied to the
\code{scope} in order to position the plot. The following code demonstrates how
to embed \code{bareBones} output in a \code{tikzpicture}:
\begin{tikzCodeBlock}[title={Example of a \TikZ{} environment including \code{bareBones} output},
code body/.append style={codebody color=white},
listing style=latexsource]
\begin{tikzpicture}
% Include bareBones output inside a scope with x and y units set to 1pt
\begin{scope}[x=1pt,y=1pt]
\input{figs/westCoast}
\end{scope}
% Label ports using coordinates placed into the barBones output by the
% tikzAnnotate function.
\foreach \name/\port in {
Longview/longView,
Coos Bay/coosBay,
Humboldt Bay/humBay,
Oakland/sfBay%
} {
\node[circle, draw, ultra thick, fill=green!60!brown!40,
outer sep=6pt,minimum size=12pt,
pin={[
draw, ultra thick,
rounded corners,
pin edge={black, ultra thick, <-, >=stealth}
] 180 : \name}] at (\port) {};
}
\end{tikzpicture}
\end{tikzCodeBlock}
\begin{figure}[H]
\centering
\begin{tikzpicture}
\begin{scope}[x=1pt,y=1pt]
\input{figs/westCoast}
\end{scope}
\foreach \name/\port in {
Longview/longView,
Coos Bay/coosBay,
Humboldt Bay/humBay,
Oakland/sfBay%
} {
\node[circle, draw, ultra thick, fill=green!60!brown!40,
outer sep=6pt,minimum size=12pt,
pin={[
draw, ultra thick,
rounded corners,
pin edge={black, ultra thick, <-, >=stealth}
] 180 : \name}] at (\port) {};
}
\end{tikzpicture}
\caption{A \TikZ{} drawing with embedded output from \code{tikz(bareBones=TRUE)}.}
\end{figure}
\subsubsection{\code{standAlone} Mode}
When the \code{standAlone} option is passed to \code{tikz()}, the resulting \code{.tex} file will be a complete \LaTeX{} document designed to be compiled on its own. This means that in addition to \verb`\begin{tikzpicture}` and \verb`\end{tikzpicture}` the file will also contain \verb`\begin{document}`, \verb`\end{document}` and a \LaTeX{} preamble. The \code{preview} package is also used in files produced by \code{standAlone} and is used to crop the pages in the resulting document to the bounding boxes of the figures that it contains. Stand-alone output may be produced in the following manner:
<<standAloneExample,echo=T,results=hide,keep.source=T>>=
require(tikzDevice)
tikz('standAloneExample.tex',standAlone=T)
plot(sin,-pi,2*pi,main="A Stand Alone TikZ Plot")
dev.off()
@
<<standAloneCompileExample, results=hide, eval=F>>=
require(tools)
catch <- system(paste(Sys.which('pdflatex'),
'-interaction=batchmode -output-directory figs/ figs/standAloneExample.tex'),
ignore.stderr=T)
# If compiling the example failed, we don't want to include a broken link.
if( catch == 0 ){
pdfLink <- "The file \\\\code{standAloneExample.tex} may then be compiled to produce
\\\\href{./figs/standAloneExample.pdf}{standAloneExample.pdf}. "
}else{
pdfLink <- ""
}
#%\Sexpr{print(pdfLink)}
@
Note that files produced using the \code{standAlone} option should not be included in \LaTeX{} documents using the \verb`\input{}` command! Use \verb`\includegraphics{}` or load the \code{pdfpages} package and use \verb`\includepdf{}`.
\subsubsection{\code{console} output Mode}
Version 0.5.0 of \pkg{tikzDevice} introduced the \code{console} option. Instead of sending its output to a file \code{tikz} will send it output to \code{stdout}. This kind of output can be redirected to a file with \code{sink()} or spit out directly into a \TeX{} document from a \lang{Sweave} file so that the \TeX{} file is self contained.
\begin{tikzCodeBlock}[title={consoleExample.Rnw},listing style=sweavechunk]
\documentclass{article}
\usepackage{tikz}
\usepackage[nogin]{Sweave}
\begin{document}
\begin{figure}[ht]
\centering
<<inline,echo=F,results=tex>>=
require(tikzDevice)
tikz(console=T,width=5,height=5)
x <- rnorm(100)
plot(x)
dummy <- dev.off()
@
\caption{caption}
\label{fig:inline}
\end{figure}
\end{document}
\end{tikzCodeBlock}
\subsubsection{Getting around special \LaTeX{} characters}
\subsubsection{Using the Global Options: An Xe\LaTeX{} example}
It is also possible to use other typesetting engines like Xe\LaTeX{} by using the global options provided by \pkg{tikzDevice}. The following example was inspired by Dario Taraborelli and his article \href{http://nitens.org/taraborelli/latex}{The Beauty of LaTeX}.
\begin{tikzCodeBlock}[title={Xe\LaTeX{} Example},listing style=sweavechunk]
#Set options for using XeLaTeX
options(tikzLatex = 'xelatex')
options(tikzDocumentDeclaration = '\\documentclass{article}')
# The preview package must be loaded first with the xetex driver option
options( tikzLatexPackages = c(
"\\usepackage[active,tightpage,xetex]{preview}"
,"\\PreviewEnvironment{pgfpicture}"
,"\\setlength\\PreviewBorder{0pt}"
,"\\usepackage{fontspec}"
,"\\usepackage[colorlinks, breaklinks, pdftitle={The Beauty of LaTeX},"
,"pdfauthor={Taraborelli, Dario}]{hyperref}"
,"\\usepackage{tikz}"
,"\\usepackage{color}"
,"\\definecolor{Gray}{rgb}{.7,.7,.7}"
,"\\definecolor{lightblue}{rgb}{.2,.5,1}"
,"\\definecolor{myred}{rgb}{1,0,0}"
,"\\newcommand{\\red}[1]{\\color{myred} #1}"
,"\\newcommand{\\reda}[1]{\\color{myred}\\fontspec[Variant=2]{Zapfino}#1}"
,"\\newcommand{\\redb}[1]{\\color{myred}\\fontspec[Variant=3]{Zapfino}#1}"
,"\\newcommand{\\redc}[1]{\\color{myred}\\fontspec[Variant=4]{Zapfino}#1}"
,"\\newcommand{\\redd}[1]{\\color{myred}\\fontspec[Variant=5]{Zapfino}#1}"
,"\\newcommand{\\rede}[1]{\\color{myred}\\fontspec[Variant=6]{Zapfino}#1}"
,"\\newcommand{\\redf}[1]{\\color{myred}\\fontspec[Variant=7]{Zapfino}#1}"
,"\\newcommand{\\redg}[1]{\\color{myred}\\fontspec[Variant=8]{Zapfino}#1}"
,"\\newcommand{\\lbl}[1]{\\color{lightblue} #1}"
,"\\newcommand{\\lbla}[1]{\\color{lightblue}\\fontspec[Variant=2]{Zapfino}#1}"
,"\\newcommand{\\lblb}[1]{\\color{lightblue}\\fontspec[Variant=3]{Zapfino}#1}"
,"\\newcommand{\\lblc}[1]{\\color{lightblue}\\fontspec[Variant=4]{Zapfino}#1}"
,"\\newcommand{\\lbld}[1]{\\color{lightblue}\\fontspec[Variant=5]{Zapfino}#1}"
,"\\newcommand{\\lble}[1]{\\color{lightblue}\\fontspec[Variant=6]{Zapfino}#1}"
,"\\newcommand{\\lblf}[1]{\\color{lightblue}\\fontspec[Variant=7]{Zapfino}#1}"
,"\\newcommand{\\lblg}[1]{\\color{lightblue}\\fontspec[Variant=8]{Zapfino}#1}"
,"\\newcommand{\\old}[1]{"
,"\\fontspec[Ligatures={Common, Rare},Variant=1,%
Swashes={LineInitial, LineFinal}]{Zapfino}"
,"\\fontsize{25pt}{30pt}\\selectfont #1}%"
,"\\newcommand{\\smallprint}[1]{\\fontspec{Hoefler Text}\\fontsize{10pt}{13pt}"%
,"\\color{Gray}\\selectfont #1}%\n"
))
#Set the content using custom defined commands
label <- c(
"\\noindent{\\red d}roo{\\lbl g}"
,"\\noindent{\\reda d}roo{\\lbla g}"
,"\\noindent{\\redb d}roo{\\lblb g}"
,"\\noindent{\\redf d}roo{\\lblf g}\\\\[.3cm]"
,"\\noindent{\\redc d}roo{\\lblc g}"
,"\\noindent{\\redd d}roo{\\lbld g}"
,"\\noindent{\\rede d}roo{\\lble g}"
,"\\noindent{\\redg d}roo{\\lblg g}\\\\[.2cm]")
#Set the titles using custom defined commands, and hyperlinks
title <- c(
"\\smallprint{D. Taraborelli (2008),
\\href{http://nitens.org/taraborelli/latex}%","{The Beauty of \\LaTeX}}"
,"\\smallprint{\\\\\\emph{Some rights reserved}.%
,"\\href{http://creativecommons.org/licenses/by-sa/3.0/}
{\\textsc{cc-by-sa}}}"
)
#Draw the graphic
lim <- 0:(length(label)+1)
tikz('xelatexEx.tex',standAlone=T,width=5,height=5)
plot(lim,lim,cex=0,pch='.',xlab = 'Xe\\LaTeX{} Test',
ylab='', main = title[1], sub = title[2])
for(i in 1:length(label))
text(i,i,label[i])
dev.off()
\end{tikzCodeBlock}
Compiling the resulting file \code{xelatexEx.tex} like so:
\begin{tikzCodeBlock}[title={Compiling with Xe\LaTeX{}},listing style=bashsource]
xelatex xelatexEx.tex
\end{tikzCodeBlock}
will produce the output in \autoref{fig:xelatex}! Please note some of the fonts used in the example may not be available on your system.
\begin{figure}[!h]
\centering
\includegraphics{img/testXeLaTeX.pdf}
\caption{Result of Xe\LaTeX{} example}\label{fig:xelatex}
\end{figure}
\newpage
\subsubsection{Annotating Graphics with \TikZ{} Commands}
The function \code{tikzAnnotate} provides the ability to annotate you graphics with \TikZ{} commands. There are a lot of exciting possibilities with this feature; It basically opens up the door for you to draw anything on your plot that can be drawn with \TikZ{}. Check out the results in \autoref{fig:annotation}.
<<annotation,echo=T,results=hide,keep.source=T>>=
require(tikzDevice)
# Load some additional TikZ libraries
tikz("annotation.tex",width=4,height=4,
packages = c(getOption('tikzLatexPackages'),
"\\usetikzlibrary{decorations.pathreplacing}",
"\\usetikzlibrary{positioning}",
"\\usetikzlibrary{shapes.arrows,shapes.symbols}")
)
p <- rgamma (300 ,1)
outliers <- which( p > quantile(p,.75)+1.5*IQR(p) )
boxplot(p)
# Add named coordinates that other TikZ commands can hook onto
tikzCoord(1, min(p[outliers]), 'min outlier')
tikzCoord(1, max(p[outliers]), 'max outlier')
# Use tikzAnnotate to insert arbitrary code, such as drawing a
# fancy path between min outlier and max outlier.
tikzAnnotate(c("\\draw[very thick,red,",
# Turn the path into a brace.
'decorate,decoration={brace,amplitude=12pt},',
# Shift it 1em to the left of the coordinates
'transform canvas={xshift=-1em}]',
'(min outlier) --',
# Add a node with some text in the middle of the path
'node[single arrow,anchor=tip,fill=white,draw=green,',
'left=14pt,text width=0.70in,align=center]',
'{Holy Outliers Batman!}', '(max outlier);'))
# tikzNode can be used to place nodes with customized options and content
tikzNode(