Debian Codegraph @

inst/examples/knitr-graphics.Rnw

raw
1 %% LyX 2.2.1 created this file. For more info, see http://www.lyx.org/.
2 %% Do not edit unless you really know what you are doing.
3 \documentclass[nohyper,justified]{tufte-handout}
4 \usepackage[T1]{fontenc}
5 \usepackage{url}
6 \usepackage[unicode=true,pdfusetitle,
7 bookmarks=true,bookmarksnumbered=true,bookmarksopen=true,bookmarksopenlevel=2,
8 breaklinks=true,pdfborder={0 0 1},backref=false,colorlinks=false]
9 {hyperref}
10 \hypersetup{
11 pdfstartview=FitH}
12 \usepackage{breakurl}
13
14 \makeatletter
15
16 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% LyX specific LaTeX commands.
17
18 \title{knitr Graphics Manual}
19 \author{Yihui Xie}
20
21 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% User specified LaTeX commands.
22 \renewcommand{\textfraction}{0.05}
23 \renewcommand{\topfraction}{0.8}
24 \renewcommand{\bottomfraction}{0.8}
25 \renewcommand{\floatpagefraction}{0.75}
26
27 \usepackage[buttonsize=1em]{animate}
28
29 \makeatother
30
31 \begin{document}
32 <<setup, include=FALSE, cache=FALSE>>=
33 library(knitr)
34 options(formatR.arrow=TRUE,width=50)
35 opts_chunk$set(fig.path='figure/graphics-', cache.path='cache/graphics-', fig.align='center', dev='tikz', fig.width=5, fig.height=5, fig.show='hold', cache=TRUE, par=TRUE)
36 knit_hooks$set(par=function(before, options, envir){
37 if (before && options$fig.show!='none') par(mar=c(4,4,.1,.1),cex.lab=.95,cex.axis=.9,mgp=c(2,.7,0),tcl=-.3)
38 }, crop=hook_pdfcrop)
39 @
40 \maketitle
41 \begin{abstract}
42 This manual shows features of graphics in the \textbf{knitr} package
43 (version \Sexpr{packageVersion('knitr')}) in detail, including the
44 graphical devices, plot recording, plot rearrangement, control of
45 plot sizes, the tikz device, figure captions, animations and other
46 types of plots such as \textbf{rgl} or GGobi plots.
47 \end{abstract}
48 Before reading this specific manual\footnote{\url{http://bit.ly/knitr-graphics-src} (Rnw source)},
49 you must have finished the main manual\footnote{\url{http://bit.ly/knitr-main}}.
50
51 \section{Graphical Devices}
52
53 The \textbf{knitr} package comes with more than 20 built-in graphical
54 devices, and you can specify them through the \texttt{dev} option.
55 This document uses the global option \texttt{dev='tikz'}, i.e., the
56 plots are recorded by the tikz device by default, but we can change
57 the device locally. Since tikz will be used extensively throughout
58 this manual and you will see plenty of tikz graphics later, now we
59 first show a few other devices.
60
61 <<test-plot, eval=FALSE>>=
62 with(trees, symbols(Height, Volume, circles = Girth/16, inches = FALSE, bg = 'deeppink', fg = 'gray30'))
63 @
64
65 \begin{marginfigure}
66 <<pdf-dev, ref.label='test-plot', dev='pdf', out.width='\\linewidth', echo=FALSE>>=
67 @
68
69 \caption{The default PDF device.\label{mar:pdf-dev}}
70 \end{marginfigure}
71
72 \begin{marginfigure}
73 <<png-dev, ref.label='test-plot', dev='png', out.width='\\linewidth', echo=FALSE>>=
74 @
75
76 \caption{The PNG device.\label{mar:png-dev}}
77 \end{marginfigure}
78
79 Figure \ref{mar:pdf-dev} and \ref{mar:png-dev} show two standard
80 devices in the \textbf{grDevices} package. We can also use devices
81 in the \textbf{Cairo} or \textbf{cairoDevice} package, e.g., the chunk
82 below uses the \emph{CairoPNG()} device in the \textbf{Cairo} package.
83
84 <<cairo-png-dev, ref.label='test-plot', dev='CairoPNG', out.width='.5\\linewidth', echo=FALSE>>=
85 @
86
87 \section{Plot Recording}
88
89 As mentioned in the main manual, \textbf{knitr} uses the \textbf{evaluate}
90 package to record plots. There are two sources of plots: first, whenever
91 \emph{plot.new()} or \emph{grid.newpage()} is called, \textbf{evaluate}
92 will try to save a snapshot of the current plot\footnote{For technical details, see \texttt{?setHook} and \texttt{?recordPlot}};
93 second, after each complete expression is evaluated, a snapshot is
94 also saved. To speed up recording, the null graphical device \texttt{pdf(file
95 = NULL)} is used. Figure \ref{fig:two-high} shows two expressions
96 producing two high-level plots.
97
98 \begin{figure}
99 <<two-high, fig.width=3, fig.height=2.5, out.width='.49\\linewidth'>>=
100 plot(cars)
101 boxplot(cars$dist,xlab='dist')
102 @
103
104 \caption{Two high-level plots are captured. The key to arrange two plots side
105 by side is to specify the \texttt{out.width} option so that each plot
106 takes less than half of the line width. We do not have to use the
107 \texttt{par(mfrow)} trick, and it may not work in some cases (e.g.
108 to put base graphics and \textbf{ggplot2} side by side; recall Figure
109 1 in the main manual).\label{fig:two-high}}
110 \end{figure}
111
112 Figure \ref{fig:low-plot-loop} shows another example of two R expressions,
113 but the second expression only involves with low-level plotting changes.
114 By default, low-level plot changes are discarded, but you can retain
115 them with the option \texttt{fig.keep='all'}.
116
117 \begin{figure}
118 <<low-plot-loop, fig.width=3, fig.height=2.5, out.width='.49\\linewidth', fig.keep='all'>>=
119 plot(0,0,type='n',ann=FALSE)
120 for(i in seq(0, 2*pi,length=20)) {points(cos(i),sin(i))}
121 @
122
123 \caption{Two complete R expressions will produce at most two plots, as long
124 as there are not multiple high-level plotting calls in each expression;
125 option \texttt{fig.keep='all'} here.\label{fig:low-plot-loop}}
126 \end{figure}
127
128 Together with \texttt{fig.show='asis'}, we can show the process of
129 plotting step by step like Figure \ref{fig:high-with-low}.
130
131 \begin{figure}
132 <<high-with-low, fig.width=3, fig.height=2.5, out.width='.5\\linewidth', fig.keep='all', fig.show='asis'>>=
133 plot(cars)
134 abline(lm(dist~speed, data=cars)) # a regression line
135 @
136
137 \caption{Low-level plot changes in base graphics can be recorded separately,
138 and plots can be put in the places where they were produced.\label{fig:high-with-low}}
139 \end{figure}
140
141 A further note on plot recording: \textbf{knitr} examines all recorded
142 plots (as R objects) and compares them sequentially; if the previous
143 plot is a ``subset'' of the next plot (= previous plot + low-level
144 changes), the previous plot will be removed when \texttt{fig.keep='high'}.
145 If two successive plots are identical, the second one will be removed
146 by default, so it might be a little bit surprising that the following
147 chunk will only produce one plot by default\footnote{adapted from \url{https://github.com/yihui/knitr/issues/41}}:
148
149 <<identical-plots,eval=FALSE>>=
150 m = matrix(1:100, ncol = 10)
151 image(m)
152 image(m*2) # exactly the same as previous plot
153 @
154
155 \section{Plot Rearrangement}
156
157 We can rearrange the plots in chunks in several ways. They can be
158 inserted right after the line(s) of R code which produced them, or
159 accumulated till the end of the chunk. There is an example in the
160 main manual demonstrating \texttt{fig.show='asis'} for two high-level
161 plots, and Figure \ref{fig:high-with-low} in this manual also demonstrates
162 this option for a high-level plot followed by a low-level change.
163
164 Here is an example demonstrating the option \texttt{fig.keep='last'}
165 (only the last plot is kept):
166
167 \begin{figure}
168 <<fig-last, fig.width=5.2, fig.height=3, out.width='.7\\linewidth', fig.keep='last', message=FALSE>>=
169 library(ggplot2)
170 pie <- ggplot(diamonds, aes(x = factor(1), fill = cut)) + xlab('cut') + geom_bar(width = 1)
171 pie + coord_polar(theta = "y") # a pie chart
172 pie + coord_polar() # the bullseye chart
173 @
174
175 \caption{Two plots were produced in this chunk, but only the last one is kept.
176 This can be useful when we experiment with many plots, but only want
177 the last result. (Adapted from the \textbf{ggplot2} website)}
178 \end{figure}
179
180 When multiple plots are produced by a code chunk, we may want to show
181 them as an animation with the option \texttt{fig.show='animate'}.
182 Figure \ref{fig:clock-animation} shows a simple clock animation;
183 you may compare the code to Figure \ref{fig:high-with-low} to understand
184 that high-level plots are always recorded, regardless of where they
185 appeared.
186
187 \begin{figure}
188 <<clock-animation, fig.width=3, fig.height=3, out.width='.4\\linewidth', fig.show='animate', tidy=FALSE, crop=TRUE>>=
189 par(mar = rep(3, 4))
190 for (i in seq(pi/2, -4/3 * pi, length = 12)) {
191 plot(0, 0, pch = 20, ann = FALSE, axes = FALSE)
192 arrows(0, 0, cos(i), sin(i))
193 axis(1, 0, "VI"); axis(2, 0, "IX")
194 axis(3, 0, "XII"); axis(4, 0, "III"); box()
195 }
196 @
197
198 \caption{A clock animation. You have to view it in Adobe Reader: click to play/pause;
199 there are also buttons to speed up or slow down the animation.\label{fig:clock-animation}}
200 \end{figure}
201
202 We can also set the alignment of plots easily with the \texttt{fig.align}
203 option; this document uses \texttt{fig.align='center'} as a global
204 option, and we can also set plots to be left/right-aligned. Figure
205 \ref{fig:maruko-plot} is an example of a left-aligned plot.
206
207 \begin{figure}
208 <<maruko-plot, fig.width=7, fig.height=4, out.width='.45\\linewidth', fig.align='left', crop=TRUE>>=
209 stars(cbind(1:16,10*(16:1)),draw.segments=TRUE)
210 @
211
212 \caption{A left-aligned plot adapted from \texttt{?stars} (I call this the
213 ``Maruko'' plot, and it is one of my favorites; see \protect\url{http://en.wikipedia.org/wiki/Chibi_Maruko-chan}).\label{fig:maruko-plot}}
214 \end{figure}
215
216
217 \section{Plot Size}
218
219 We have seen several examples in which two or more plots can be put
220 side by side, and this is because the plots were resized in the output
221 document; with the chunk option \texttt{out.width} less than half
222 of the line width, \LaTeX{} will arrange two plots in one line; if
223 it is less than $1/3$ of the line width, three plots can be put in
224 one line. Of course we can also set it to be an absolute width like
225 \texttt{3in} (3 inches). This option is used extensively in this document
226 to control the size of plots in the output document.
227
228 \section{The tikz Device}
229
230 The main advantage of using tikz graphics is the consistency of styles
231 between texts in plots and those in the main document. Since we can
232 use native \LaTeX{} commands in plots, the styles of texts in plots
233 can be very sophisticated (see Figure \ref{fig:math-formula-tt} for
234 an example).
235
236 \begin{figure}
237 <<math-formula-tt, fig.width=6, fig.height=2, out.width='\\linewidth'>>=
238 plot(0:1,0:1,type='n', ylab='origin of statistics', xlab='statistical presentation rocks with \\LaTeX{}')
239 text(.5,c(.8,.5,.2), c('\\texttt{lm(y \\textasciitilde{} x)}', '$\\hat{\\beta}=(X^{\\prime}X)^{-1}X^{\\prime}y$', '$(\\Omega,\\mathcal{F},\\mu)$'))
240 @
241
242 \caption{A plot created by \textbf{tikzDevice} with math expressions and typewriter
243 fonts. Note the font style consistency \textendash{} we write the
244 same expressions in \protect\LaTeX{} here: $\hat{\beta}=(X^{\prime}X)^{-1}X^{\prime}y$
245 and $(\Omega,\mathcal{F},\mu)$; also \texttt{lm(y \textasciitilde{}
246 x)}.\label{fig:math-formula-tt}}
247 \end{figure}
248
249 When using Xe\LaTeX{} instead of PDF\LaTeX{} to compile the document,
250 we need to tell the \textbf{tikzDevice} package by setting the \texttt{tikzDefaultEngine}
251 option before all plot chunks (preferably in the first chunk):
252
253 <<xetex-tikz, eval=FALSE>>=
254 options(tikzDefaultEngine='xetex')
255 @
256
257 This is useful and often necessary to compile tikz plots which contain
258 (UTF8) multi-byte characters.
259
260 \section{Figure Caption}
261
262 If the chunk option \texttt{fig.cap} is not \texttt{NULL} or \texttt{NA},
263 the plots will be put in a \texttt{figure} environment when the output
264 format is \LaTeX{}, and this option is used to write a caption in
265 this environment using \texttt{\textbackslash{}caption\{\}}. The other
266 two related options are \texttt{fig.scap} and \texttt{fig.lp} which
267 set the short caption and a prefix string for the figure label. The
268 default short caption is extracted from the caption by truncating
269 it at the first period or colon or semi-colon. The label is a combination
270 of \texttt{fig.lp} and the chunk label. Because \texttt{figure} is
271 a float environment, it can float away from the chunk output to other
272 places such as the top or bottom of a page when the \TeX{} document
273 is compiled.
274
275 \section{Other Features}
276
277 The \textbf{knitr} package can be extended with hook functions, and
278 here I give a few examples illustrating the flexibility.
279
280 \subsection{Cropping PDF Graphics}
281
282 Some R users may have been suffering from the extra margins in R plots,
283 especially in base graphics (\textbf{ggplot2} is much better in this
284 aspect). The default graphical option \texttt{mar} is about \texttt{c(5,
285 4, 4, 2)} (see \texttt{?par}), which is often too big. Instead of
286 endlessly setting \texttt{par(mar)}, you may consider the program
287 \texttt{pdfcrop}, which can crop the white margin automatically\footnote{\url{http://www.ctan.org/pkg/pdfcrop}}.
288 In \textbf{knitr}, we can set up the hook \emph{hook\_pdfcrop()} to
289 work with a chunk option, say, \texttt{crop}.
290
291 <<crop-hook, cache=FALSE>>=
292 knit_hooks$set(crop=hook_pdfcrop)
293 @
294
295 Now we compare two plots below. The first one is not cropped (Figure
296 \ref{fig:pdf-nocrop}); then the same plot is produced but with a
297 chunk option \texttt{crop=TRUE} which will call the cropping hook
298 (Figure \ref{fig:pdf-crop}).
299
300 \begin{figure}
301 \begin{kframe}
302 <<pdf-nocrop, fig.width=3.2, fig.height=3.2, out.width='.5\\linewidth'>>=
303 par(mar=c(5,4,4,2),bg='white') # large margin
304 plot(lat~long,data=quakes,pch=20,col=rgb(0,0,0,.2))
305 @
306 \end{kframe}
307
308 \caption{The original plot produced in R, with a large margin.\label{fig:pdf-nocrop}}
309 \end{figure}
310
311 \begin{figure}
312 \begin{kframe}
313 <<pdf-crop, ref.label='pdf-nocrop', echo=FALSE, fig.width=3.2, fig.height=3.2, out.width='.5\\linewidth', crop=TRUE>>=
314 @
315 \end{kframe}
316
317 \caption{The cropped plot; it fits better in the document.\label{fig:pdf-crop}}
318 \end{figure}
319
320 As we can see, the white margins are gone. If we use \emph{par()},
321 it might be hard and tedious to figure out a reasonable amount of
322 margin in order that neither is any label cropped nor do we get a
323 too large margin. My experience is that \texttt{pdfcrop} works well
324 with base graphics, but barely works with \textbf{grid} graphics (therefore
325 \textbf{lattice} and \textbf{ggplot2} are ruled out).
326
327 \subsection{Manually Saved Plots}
328
329 We have explained how R plots are recorded before. In some cases,
330 it is not possible to capture plots by \emph{recordPlot()} (such as
331 \textbf{rgl} plots), but we can save them using other functions. To
332 insert these plots into the output, we need to set up a hook first
333 like this (see \texttt{?hook\_plot\_custom} for details):
334
335 <<custom-plot-hook, cache=FALSE>>=
336 knit_hooks$set(custom.plot = hook_plot_custom)
337 @
338
339 Then we set the chunk option \texttt{custom.plot=TRUE}, and manually
340 write plot files in the chunk. Here we show an example of capturing
341 GGobi plots using the function \emph{ggobi\_display\_save\_picture()}
342 in the \textbf{rggobi} package:
343
344 <<ggobi-plot, custom.plot=TRUE, fig.ext='png', out.width='2.5in', results='hide', warning=FALSE>>=
345 library(rggobi)
346 ggobi(ggobi_find_file('data', 'flea.csv'))
347 Sys.sleep(1) # wait for snapshot
348 ggobi_display_save_picture(path=fig_path('.png'))
349 @
350
351 One thing to note here is we have to make sure the plot filename is
352 from \emph{fig\_path()}, which is a convenience function to return
353 the figure path for the current chunk.
354
355 We can do whatever normal R plots can do with this hook, and we give
356 another example below to show how to work with animations.
357
358 <<rgl-animation, custom.plot=TRUE, fig.ext='png', out.width='2.5in', fig.show='animate', fig.num=20, interval=.4, aniopts='controls,autoplay', results='hide', warning=FALSE>>=
359 library(animation) # adapted from demo('rgl_animation')
360 data(pollen)
361 uM = matrix(c(-0.37, -0.51, -0.77, 0, -0.73, 0.67, -0.1, 0, 0.57, 0.53, -0.63, 0, 0, 0, 0, 1), 4, 4)
362 library(rgl)
363 open3d(userMatrix = uM, windowRect = c(0, 0, 400, 400))
364 plot3d(pollen[, 1:3])
365 zm = seq(1, 0.05, length = 20)
366 par3d(zoom = 1) # change the zoom factor gradually later
367 for (i in 1:length(zm)) {
368 par3d(zoom = zm[i]); Sys.sleep(.05)
369 rgl.snapshot(fig_path('png', number = i))
370 }
371 @
372
373 \subsection{rgl Plots}
374
375 With the hook \emph{hook\_rgl()}, we can easily save snapshots from
376 the \textbf{rgl} package. We have shown an example in the main manual,
377 and here we add some details. The rgl hook is a good example of taking
378 care of details by carefully using the \texttt{options} argument in
379 the hook; for example, we cannot directly set the width and height
380 of rgl plots in \emph{rgl.snapshot()} or \emph{rgl.postscript()},
381 so we make use of the options \texttt{fig.width}, \texttt{fig.height}
382 and \texttt{dpi} to calculate the expected size of the window, then
383 resize the current window by \emph{par3d()}, and finally save the
384 plot.
385
386 This hook is actually built upon \emph{hook\_plot\_custom()} \textendash{}
387 first it saves the \textbf{rgl} snapshot, then it calls \emph{hook\_plot\_custom()}
388 to write the output code.
389
390 \appendix
391
392 \section{How to Compile This Manual}
393
394 This manual has a long chain of dependencies, so it may not be easy
395 to compile. These packages are required (all of them are free software):
396 \begin{description}
397 \item [{R}] Cairo, ggplot2, tikzDevice, rgl, rggobi, animation (all available
398 on CRAN except tikzDevice which is on R-Forge for the time being)
399 \item [{\LaTeX{}}] animate, hyperref and the tufte-handout class
400 \item [{Other}] GGobi, pdfcrop
401 \end{description}
402
403 \end{document}