Skip to content

Instantly share code, notes, and snippets.

@jeroen
Last active December 18, 2015 17:09
Show Gist options
  • Save jeroen/5816686 to your computer and use it in GitHub Desktop.
Save jeroen/5816686 to your computer and use it in GitHub Desktop.
knitr examples

A minimal R Markdown example

A quote:

Markdown is not LaTeX.

To compile me, run this in R:

library(knitr)
knit('001-minimal.Rmd')

See output here.

code chunks

A paragraph here. A code chunk below (remember the three backticks):

1 + 1
## [1] 2
0.4 - 0.7 + 0.3  # what? it is not zero!
## [1] 5.551e-17

graphics

It is easy.

plot(1:10)

plot of chunk unnamed-chunk-2

hist(rnorm(1000))

plot of chunk unnamed-chunk-2

inline code

Yes I know the value of pi is 3.1416, and 2 times pi is 6.2832.

math

Sigh. You cannot live without math equations. OK, here we go: $\alpha+\beta=\gamma$. Note this is not supported by native markdown. You probably want to try RStudio, or at least the R package markdown, or the function knitr::knit2html().

nested code chunks

You can write code within other elements, e.g. a list

  1. foo is good

    strsplit("hello indented world", " ")[[1]]
    ## [1] "hello"    "indented" "world"
    
  2. bar is better

conclusion

Nothing fancy. You are ready to go. When you become picky, go to the knitr website.

knitr logo

# A minimal R Markdown example
A quote:
> Markdown is not LaTeX.
To compile me, run this in R:
library(knitr)
knit('001-minimal.Rmd')
See [output here](https://github.com/yihui/knitr-examples/blob/master/001-minimal.md).
## code chunks
A _paragraph_ here. A code chunk below (remember the three backticks):
```{r}
1+1
.4-.7+.3 # what? it is not zero!
```
## graphics
It is easy.
```{r}
plot(1:10)
hist(rnorm(1000))
```
## inline code
Yes I know the value of pi is `r pi`, and 2 times pi is `r 2*pi`.
## math
Sigh. You cannot live without math equations. OK, here we go: $\alpha+\beta=\gamma$. Note this is not supported by native markdown. You probably want to try RStudio, or at least the R package **markdown**, or the function `knitr::knit2html()`.
## nested code chunks
You can write code within other elements, e.g. a list
1. foo is good
```{r}
strsplit('hello indented world', ' ')[[1]]
```
2. bar is better
## conclusion
Nothing fancy. You are ready to go. When you become picky, go to the [knitr website](http://yihui.name/knitr/).
![knitr logo](http://yihui.name/knitr/images/knit-logo.png)
\documentclass{article}
\begin{document}
Here is a code chunk.
<<foo, fig.height=4>>=
1+1
letters
chartr('xie', 'XIE', c('xie yihui', 'Yihui Xie'))
par(mar=c(4, 4, .2, .2)); plot(rnorm(100))
@
You can also write inline expressions, e.g. $\pi=\Sexpr{pi}$, and \Sexpr{1.598673e8} is a big number.
\end{document}
\documentclass{article}\usepackage[]{graphicx}\usepackage[]{color}
%% maxwidth is the original width if it is less than linewidth
%% otherwise use linewidth (to make sure the graphics do not exceed the margin)
\makeatletter
\def\maxwidth{ %
\ifdim\Gin@nat@width>\linewidth
\linewidth
\else
\Gin@nat@width
\fi
}
\makeatother
\definecolor{fgcolor}{rgb}{0.2, 0.2, 0.2}
\newcommand{\hlnumber}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlfunctioncall}[1]{\textcolor[rgb]{0.501960784313725,0,0.329411764705882}{\textbf{#1}}}%
\newcommand{\hlstring}[1]{\textcolor[rgb]{0.6,0.6,1}{#1}}%
\newcommand{\hlkeyword}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlargument}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlcomment}[1]{\textcolor[rgb]{0.180392156862745,0.6,0.341176470588235}{#1}}%
\newcommand{\hlroxygencomment}[1]{\textcolor[rgb]{0.43921568627451,0.47843137254902,0.701960784313725}{#1}}%
\newcommand{\hlformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hleqformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlassignement}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlpackage}[1]{\textcolor[rgb]{0.588235294117647,0.709803921568627,0.145098039215686}{#1}}%
\newcommand{\hlslot}[1]{\textit{#1}}%
\newcommand{\hlsymbol}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlprompt}[1]{\textcolor[rgb]{0.2,0.2,0.2}{#1}}%
\usepackage{framed}
\makeatletter
\newenvironment{kframe}{%
\def\at@end@of@kframe{}%
\ifinner\ifhmode%
\def\at@end@of@kframe{\end{minipage}}%
\begin{minipage}{\columnwidth}%
\fi\fi%
\def\FrameCommand##1{\hskip\@totalleftmargin \hskip-\fboxsep
\colorbox{shadecolor}{##1}\hskip-\fboxsep
% There is no \\@totalrightmargin, so:
\hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth}%
\MakeFramed {\advance\hsize-\width
\@totalleftmargin\z@ \linewidth\hsize
\@setminipage}}%
{\par\unskip\endMakeFramed%
\at@end@of@kframe}
\makeatother
\definecolor{shadecolor}{rgb}{.97, .97, .97}
\definecolor{messagecolor}{rgb}{0, 0, 0}
\definecolor{warningcolor}{rgb}{1, 0, 1}
\definecolor{errorcolor}{rgb}{1, 0, 0}
\newenvironment{knitrout}{}{} % an empty environment to be redefined in TeX
\usepackage{alltt}
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
\begin{document}
Here is a code chunk.
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
1 + 1
\end{alltt}
\begin{verbatim}
## [1] 2
\end{verbatim}
\begin{alltt}
letters
\end{alltt}
\begin{verbatim}
## [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q"
## [18] "r" "s" "t" "u" "v" "w" "x" "y" "z"
\end{verbatim}
\begin{alltt}
\hlfunctioncall{chartr}(\hlstring{"xie"}, \hlstring{"XIE"}, \hlfunctioncall{c}(\hlstring{"xie yihui"}, \hlstring{"Yihui Xie"}))
\end{alltt}
\begin{verbatim}
## [1] "XIE yIhuI" "YIhuI XIE"
\end{verbatim}
\begin{alltt}
\hlfunctioncall{par}(mar = \hlfunctioncall{c}(4, 4, 0.2, 0.2))
\hlfunctioncall{plot}(\hlfunctioncall{rnorm}(100))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/002-minimal-foo}
\end{knitrout}
You can also write inline expressions, e.g. $\pi=3.1416$, and \ensuremath{1.5987\times 10^{8}} is a big number.
\end{document}
<!DOCTYPE html>
<html>
<head>
<style type="text/css">.knitr.inline {
background-color: #f7f7f7;
border:solid 1px #B0B0B0;
}
.error {
font-weight: bold;
color: #FF0000;
},
.warning {
font-weight: bold;
}
.message {
font-style: italic;
}
.source, .output, .warning, .error, .message {
padding: 0em 1em;
border:solid 1px #F7F7F7;
}
.source {
background-color: #f7f7f7;
}
.rimage.left {
text-align: left;
}
.rimage.right {
text-align: right;
}
.rimage.center {
text-align: center;
}
.source {
color: #333333;
}
.background {
color: #F7F7F7;
}
.number {
color: #000000;
}
.functioncall {
color: #800054;
font-weight: bolder;
}
.string {
color: #9999FF;
}
.keyword {
font-weight: bolder;
color: black;
}
.argument {
color: #B04005;
}
.comment {
color: #2E9957;
}
.roxygencomment {
color: #707AB3;
}
.formalargs {
color: #B04005;
}
.eqformalargs {
color: #B04005;
}
.assignement {
font-weight: bolder;
color: #000000;
}
.package {
color: #96B525;
}
.slot {
font-style: italic;
}
.symbol {
color: #000000;
}
.prompt {
color: #333333;
}
</style>
<title>A minimal knitr example in HTML</title>
</head>
<body>
<div class="chunk" id="unnamed-chunk-1"><div class="rcode"><div class="source"><pre class="knitr r">opts_chunk$<span class="functioncall">set</span>(fig.width = 5, fig.height = 5)
</pre></div>
</div></div>
<p>This is a minimal example which shows <strong>knitr</strong>
working with HTML
pages. See <a href="https://bitbucket.org/stat/knitr/downloads/003-minimal.html">here</a>
for the output and
<a href="https://github.com/yihui/knitr-examples/blob/master/003-minimal.Rhtml">here</a>
for the source.</p>
<p>Boring stuff as usual:</p>
<div class="chunk" id="unnamed-chunk-2"><div class="rcode"><div class="source"><pre class="knitr r"><span class="comment">## a simple calculator</span>
1 + 1
</pre></div>
<div class="output"><pre class="knitr r">## [1] 2
</pre></div>
<div class="source"><pre class="knitr r"><span class="comment">## boring random numbers</span>
<span class="functioncall">set.seed</span>(123)
<span class="functioncall">rnorm</span>(5)
</pre></div>
<div class="output"><pre class="knitr r">## [1] -0.56048 -0.23018 1.55871 0.07051 0.12929
</pre></div>
</div></div>
<p>We can also produce plots (centered by the
option <code>fig.align='center'</code>):</p>
<div class="chunk" id="html-cars-scatter"><div class="rcode"><div class="source"><pre class="knitr r"><span class="functioncall">library</span>(ggplot2)
<span class="functioncall">plot</span>(mpg ~ hp, mtcars)
</pre></div>
</div><div class="rimage center"><img src="http://animation.r-forge.r-project.org/knitr-ex/figure/003-minimal-html-cars-scatter1.png" title="plot of chunk html-cars-scatter" alt="plot of chunk html-cars-scatter" class="plot" /></div><div class="rcode">
<div class="source"><pre class="knitr r"><span class="functioncall">qplot</span>(hp, mpg, data = mtcars) + <span class="functioncall">geom_smooth</span>()
</pre></div>
</div><div class="rimage center"><img src="http://animation.r-forge.r-project.org/knitr-ex/figure/003-minimal-html-cars-scatter2.png" title="plot of chunk html-cars-scatter" alt="plot of chunk html-cars-scatter" class="plot" /></div></div>
<p>Errors, messages and warnings can be put into <code>div</code>'s
with different <code>class</code>es:</p>
<div class="chunk" id="unnamed-chunk-3"><div class="rcode"><div class="source"><pre class="knitr r"><span class="functioncall">sqrt</span>(-1) # warning
</pre></div>
<div class="warning"><pre class="knitr r">## Warning: NaNs produced
</pre></div>
<div class="output"><pre class="knitr r">## [1] NaN
</pre></div>
<div class="source"><pre class="knitr r"><span class="functioncall">message</span>(<span class="string">"knitr says hello to HTML!"</span>)
</pre></div>
<div class="message"><pre class="knitr r">## knitr says hello to HTML!
</pre></div>
<div class="source"><pre class="knitr r">1 + <span class="string">"a"</span> # mission impossible
</pre></div>
<div class="error"><pre class="knitr r">## Error: non-numeric argument to binary operator
</pre></div>
</div></div>
<p>In the end, let's show off a 3D plot from
the <strong>rgl</strong> package.</p>
<div class="chunk" id="unnamed-chunk-4"><div class="rcode"><div class="source"><pre class="knitr r">knit_hooks$<span class="functioncall">set</span>(rgl = hook_rgl) # set up the hook first
</pre></div>
</div></div>
<div class="chunk" id="fancy-rgl"><div class="rcode"><div class="source"><pre class="knitr r"><span class="functioncall"><span class="keyword">if</span></span> (<span class="functioncall">require</span>(<span class="string">"rgl"</span>)) {
<span class="functioncall">demo</span>(<span class="string">"bivar"</span>, package = <span class="string">"rgl"</span>, echo = <span class="keyword">FALSE</span>)
<span class="functioncall">par3d</span>(zoom = 0.7)
}
</pre></div>
<div class="message"><pre class="knitr r">## Loading required package: MASS
</pre></div>
</div><div class="rimage center"><img src="http://animation.r-forge.r-project.org/knitr-ex/figure/003-minimal-fancy-rgl.png" title="plot of chunk fancy-rgl" alt="plot of chunk fancy-rgl" class="plot" /></div></div>
<p>Well, everything seems to be working. Let's ask R what is the
value of &pi;? Of course it is <code class="knitr inline">3.1416</code>.</p>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>A minimal knitr example in HTML</title>
</head>
<body>
<!--begin.rcode
opts_chunk$set(fig.width=5, fig.height=5)
end.rcode-->
<p>This is a minimal example which shows <strong>knitr</strong>
working with HTML
pages. See <a href="https://bitbucket.org/stat/knitr/downloads/003-minimal.html">here</a>
for the output and
<a href="https://github.com/yihui/knitr-examples/blob/master/003-minimal.Rhtml">here</a>
for the source.</p>
<p>Boring stuff as usual:</p>
<!--begin.rcode
## a simple calculator
1+1
## boring random numbers
set.seed(123)
rnorm(5)
end.rcode-->
<p>We can also produce plots (centered by the
option <code>fig.align='center'</code>):</p>
<!--begin.rcode html-cars-scatter, message=FALSE, fig.align='center'
library(ggplot2)
plot(mpg~hp, mtcars)
qplot(hp, mpg, data=mtcars)+geom_smooth()
end.rcode-->
<p>Errors, messages and warnings can be put into <code>div</code>'s
with different <code>class</code>es:</p>
<!--begin.rcode
sqrt(-1) # warning
message('knitr says hello to HTML!')
1+'a' # mission impossible
end.rcode-->
<p>In the end, let's show off a 3D plot from
the <strong>rgl</strong> package.</p>
<!--begin.rcode
knit_hooks$set(rgl = hook_rgl) # set up the hook first
end.rcode-->
<!--begin.rcode fancy-rgl, rgl=TRUE, fig.align='center', fig.width=4, fig.height=4
if (require('rgl')) {
demo('bivar', package='rgl', echo=FALSE)
par3d(zoom=.7)
}
end.rcode-->
<p>Well, everything seems to be working. Let's ask R what is the
value of &pi;? Of course it is <!--rinline pi -->.</p>
</body>
</html>
We know the value of pi is <% pi %>, and 2 times pi is <% 2*pi %>.
The brew syntax in knitr is similar to the brew package, but all kinds of
syntax in the brew package will be treated in the same way in knitr: they are
nothing but inline R code.
<% x<-1.234; NULL %>
You can write a number as <% x %>, or <%= x %>, or <% x -%>.
We know the value of pi is 3.1416, and 2 times pi is 6.2832.
The brew syntax in knitr is similar to the brew package, but all kinds of
syntax in the brew package will be treated in the same way in knitr: they are
nothing but inline R code.
You can write a number as 1.234, or 1.234, or 1.234.
\documentclass{article}
\usepackage{graphicx}
%% for inline R code: if the inline code is not correctly parsed, you will see a message
\newcommand{\rinline}[1]{SOMETHING WRONG WITH knitr}
%% begin.rcode setup, include=FALSE
% opts_chunk$set(fig.path='figure/latex-', cache.path='cache/latex-')
%% end.rcode
\begin{document}
Boring stuff as usual:
%% a chunk with default options
%% begin.rcode
% 1+1
%
% x=rnorm(5)
%% end.rcode
For the cached chunk below, you will need to wait for 10 seconds for
the first time you compile this document, but it takes no time the
next time you run it again.
%% chunk options: cache this chunk
%% begin.rcode my-cache, cache=TRUE
% set.seed(123)
% x = runif(10)
% sd(x) # standard deviation
%
% Sys.sleep(10) # test cache
%% end.rcode
Now we know the first element of x is \rinline{x[1]}. And we also know
the 26 letters are \rinline{LETTERS}. An expression that returns a
value of length 0 will be removed from the output, \rinline{x[1] =
2011; NULL} but it was indeed evaluated, e.g. now the first element
of x becomes \rinline{x[1]}.
How about figures? Let's use the Cairo PDF device (assumes R $\geq$
2.14.0).
%% begin.rcode cairo-scatter, dev='cairo_pdf', fig.width=5, fig.height=5, out.width='.8\\textwidth'
% plot(cars) # a scatter plot
%% end.rcode
Warnings, messages and errors are preserved by default.
%% begin.rcode
% sqrt(-1) # here is a warning!
% message('this is a message you should know')
% 1+'a' # impossible
%% end.rcode
\end{document}
\documentclass{article}\usepackage[]{graphicx}\usepackage[]{color}
%% maxwidth is the original width if it is less than linewidth
%% otherwise use linewidth (to make sure the graphics do not exceed the margin)
\makeatletter
\def\maxwidth{ %
\ifdim\Gin@nat@width>\linewidth
\linewidth
\else
\Gin@nat@width
\fi
}
\makeatother
\definecolor{fgcolor}{rgb}{0.2, 0.2, 0.2}
\newcommand{\hlnumber}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlfunctioncall}[1]{\textcolor[rgb]{0.501960784313725,0,0.329411764705882}{\textbf{#1}}}%
\newcommand{\hlstring}[1]{\textcolor[rgb]{0.6,0.6,1}{#1}}%
\newcommand{\hlkeyword}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlargument}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlcomment}[1]{\textcolor[rgb]{0.180392156862745,0.6,0.341176470588235}{#1}}%
\newcommand{\hlroxygencomment}[1]{\textcolor[rgb]{0.43921568627451,0.47843137254902,0.701960784313725}{#1}}%
\newcommand{\hlformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hleqformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlassignement}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlpackage}[1]{\textcolor[rgb]{0.588235294117647,0.709803921568627,0.145098039215686}{#1}}%
\newcommand{\hlslot}[1]{\textit{#1}}%
\newcommand{\hlsymbol}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlprompt}[1]{\textcolor[rgb]{0.2,0.2,0.2}{#1}}%
\usepackage{framed}
\makeatletter
\newenvironment{kframe}{%
\def\at@end@of@kframe{}%
\ifinner\ifhmode%
\def\at@end@of@kframe{\end{minipage}}%
\begin{minipage}{\columnwidth}%
\fi\fi%
\def\FrameCommand##1{\hskip\@totalleftmargin \hskip-\fboxsep
\colorbox{shadecolor}{##1}\hskip-\fboxsep
% There is no \\@totalrightmargin, so:
\hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth}%
\MakeFramed {\advance\hsize-\width
\@totalleftmargin\z@ \linewidth\hsize
\@setminipage}}%
{\par\unskip\endMakeFramed%
\at@end@of@kframe}
\makeatother
\definecolor{shadecolor}{rgb}{.97, .97, .97}
\definecolor{messagecolor}{rgb}{0, 0, 0}
\definecolor{warningcolor}{rgb}{1, 0, 1}
\definecolor{errorcolor}{rgb}{1, 0, 0}
\newenvironment{knitrout}{}{} % an empty environment to be redefined in TeX
\usepackage{alltt}
\usepackage{graphicx}
%% for inline R code: if the inline code is not correctly parsed, you will see a message
\newcommand{\rinline}[1]{SOMETHING WRONG WITH knitr}
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
\begin{document}
Boring stuff as usual:
%% a chunk with default options
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
1 + 1
\end{alltt}
\begin{verbatim}
## [1] 2
\end{verbatim}
\begin{alltt}
x = \hlfunctioncall{rnorm}(5)
\end{alltt}
\end{kframe}
\end{knitrout}
For the cached chunk below, you will need to wait for 10 seconds for
the first time you compile this document, but it takes no time the
next time you run it again.
%% chunk options: cache this chunk
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlfunctioncall{set.seed}(123)
x = \hlfunctioncall{runif}(10)
\hlfunctioncall{sd}(x) \hlcomment{# standard deviation}
\end{alltt}
\begin{verbatim}
## [1] 0.2947
\end{verbatim}
\begin{alltt}
\hlfunctioncall{Sys.sleep}(10) \hlcomment{# test cache}
\end{alltt}
\end{kframe}
\end{knitrout}
Now we know the first element of x is 0.2876. And we also know
the 26 letters are A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z. An expression that returns a
value of length 0 will be removed from the output, but it was indeed evaluated, e.g. now the first element
of x becomes 2011.
How about figures? Let's use the Cairo PDF device (assumes R $\geq$
2.14.0).
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlfunctioncall{plot}(cars) \hlcomment{# a scatter plot}
\end{alltt}
\end{kframe}
\includegraphics[width=.8\textwidth]{figure/latex-cairo-scatter}
\end{knitrout}
Warnings, messages and errors are preserved by default.
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlfunctioncall{sqrt}(-1) \hlcomment{# here is a warning!}
\end{alltt}
{\ttfamily\noindent\color{warningcolor}{\#\# Warning: NaNs produced}}\begin{verbatim}
## [1] NaN
\end{verbatim}
\begin{alltt}
\hlfunctioncall{message}(\hlstring{"this is a message you should know"})
\end{alltt}
{\ttfamily\noindent\itshape\color{messagecolor}{\#\# this is a message you should know}}\begin{alltt}
1 + \hlstring{"a"} # impossible
\end{alltt}
{\ttfamily\noindent\bfseries\color{errorcolor}{\#\# Error: non-numeric argument to binary operator}}\end{kframe}
\end{knitrout}
\end{document}
A reST document for knitr
=========================
This is a reStructuredText document. The input filename extension is ``Rrst``
and the output filename will be ``rst``. Here is how we write R code in
**knitr**:
.. {r setup}
options(width = 75)
# do not use the sourcecode directive
render_rst(strict=TRUE)
# global chunk options
opts_chunk$set(cache=TRUE, fig.width=5, fig.height=5)
.. ..
More examples
-------------
A code chunk begins with ``.. {r label, options}``, and ends with ``.. ..``
(note the space in between). Optionally you can precede all R code with two
dots, e.g.
.. {r rst-example}
.. 1+1
.. set.seed(123); rnorm(10)
.. warning('do not forget the space after ..!')
.. ..
Here is a plot:
.. {r rst-plot, out.width='360px', fig.cap='A ggplot2 example'}
library(ggplot2)
qplot(hp, mpg, data=mtcars) + geom_smooth()
.. ..
Inline R code is like this: the value of pi is :r:`pi`.

A reST document for knitr

This is a reStructuredText document. The input filename extension is Rrst and the output filename will be rst. Here is how we write R code in knitr:

options(width = 75)
# do not use the sourcecode directive
render_rst(strict = TRUE)

# global chunk options
opts_chunk$set(cache = TRUE, fig.width = 5, fig.height = 5)

More examples

A code chunk begins with .. {r label, options}, and ends with .. .. (note the space in between). Optionally you can precede all R code with two dots, e.g.

1 + 1
## [1] 2
set.seed(123)
rnorm(10)
##  [1] -0.56048 -0.23018  1.55871  0.07051  0.12929  1.71506  0.46092
##  [8] -1.26506 -0.68685 -0.44566
warning("do not forget the space after ..!")
## Warning: do not forget the space after ..!

Here is a plot:

library(ggplot2)
## Loading required package: methods
qplot(hp, mpg, data = mtcars) + geom_smooth()
## geom_smooth: method="auto" and size of largest group is <1000, so using
## loess. Use 'method = x' to change the smoothing method.
A ggplot2 example

A ggplot2 example

Inline R code is like this: the value of pi is 3.1416.

Testing text output

See if chunk options like tidy, prompt and echo, etc work as expected.

A normal chunk

1 + 1
## [1] 2
for (i in 1:10) {
    # nothing before 10
    if (i >= 10) 
        print(i)
}
## [1] 10
# two blank lines below


dnorm(0)
## [1] 0.3989

Do not evaluate

1 + 1
for (i in 1:10) {
    # nothing before 10
    if (i >= 10) 
        print(i)
}
# two blank lines below


dnorm(0)

Add prompts

> 1 + 1
## [1] 2
> for (i in 1:10) {
+     # nothing before 10
+     if (i >= 10) 
+         print(i)
+ }
## [1] 10
> # two blank lines below
> 
> 
> dnorm(0)
## [1] 0.3989

No evaluate or tidy

1+1
for (i in 1:10) {
# nothing before 10
if(i>=10)print(i)
}
# two blank lines below


dnorm(0)

Do not tidy

1+1
## [1] 2
for (i in 1:10) {
# nothing before 10
if(i>=10)print(i)
}
## [1] 10
# two blank lines below


dnorm(0)
## [1] 0.3989

Do not echo

## [1] 2
## [1] 10
## [1] 0.3989

Do not comment out results

1 + 1
[1] 2
for (i in 1:10) {
    # nothing before 10
    if (i >= 10) 
        print(i)
}
[1] 10
# two blank lines below


dnorm(0)
[1] 0.3989

Do not echo the 2nd expression

1 + 1
## [1] 2
## [1] 10
# two blank lines below


dnorm(0)
## [1] 0.3989

Do not evaluate, echo the 2nd expression

for (i in 1:10) {
    # nothing before 10
    if (i >= 10) 
        print(i)
}

Only evaluate the first two expressions

1 + 1
## [1] 2
for (i in 1:10) {
    # nothing before 10
    if (i >= 10) 
        print(i)
}
## [1] 10
## # two blank lines below
## 
## 
## dnorm(0)

Add prompts but no tidy

> 1+1
## [1] 2
> for (i in 1:10) {
+ # nothing before 10
+ if(i>=10)print(i)
+ }
## [1] 10
> # two blank lines below
> 
> 
> dnorm(0)
## [1] 0.3989

Change prompts

options(prompt = "R> ", continue = "+  ")
R> 1 + 1
## [1] 2
R> for (i in 1:10) {
+      # nothing before 10
+      if (i >= 10) 
+          print(i)
+  }
## [1] 10
R> # two blank lines below
R> 
R> 
R> dnorm(0)
## [1] 0.3989

Backslashes

{
    # can you deal with \code{foo} or \n, \a?
    gsub("\\.", "\\\\", "a.b.c")  # \link{bar}
}
## [1] "a\\b\\c"
cat("a\tb\nc")
## a	b
## c

Other formatR options

We can set formatR options globally:

options(keep.blank.line = FALSE)
1 + 1
for (i in 1:10) {
    # nothing before 10
    if (i >= 10) 
        print(i)
}
# two blank lines below
dnorm(0)

Or locally in one chunk via tidy.opts. Do not keep comments:

1 + 1
for (i in 1:10) {
    if (i >= 10) 
        print(i)
}
dnorm(0)

Move left braces to the next line:

for (i in 1:10)
{
    # nothing before 10
    if (i >= 10) 
        print(i)
}
## [1] 10

Indent by 2 spaces:

1 + 1
for (i in 1:10) {
  # nothing before 10
  if (i >= 10) 
    print(i)
}
# two blank lines below
dnorm(0)

See http://yihui.name/formatR for details.

Empty chunks

# Testing text output
See if chunk options like `tidy`, `prompt` and `echo`, etc work as expected.
## A normal chunk
```{r demo}
1+1
for (i in 1:10) {
# nothing before 10
if(i>=10)print(i)
}
# two blank lines below
dnorm(0)
```
## Do not evaluate
```{r demo, eval=FALSE}
```
## Add prompts
```{r demo, prompt=TRUE}
```
## No evaluate or tidy
```{r demo, eval=FALSE, tidy=FALSE}
```
## Do not tidy
```{r demo, tidy=FALSE}
```
## Do not echo
```{r demo, echo=FALSE}
```
## Do not comment out results
```{r demo, comment=NA}
```
## Do not echo the 2nd expression
```{r demo, echo=-2}
```
## Do not evaluate, echo the 2nd expression
```{r demo, eval=FALSE, echo=2}
```
## Only evaluate the first two expressions
```{r demo, eval=1:2}
```
## Add prompts but no tidy
```{r demo, tidy=FALSE, prompt=TRUE}
```
## Change prompts
```{r}
options(prompt='R> ', continue='+ ')
```
```{r demo, prompt=TRUE}
```
## Backslashes
```{r}
{
# can you deal with \code{foo} or \n, \a?
gsub('\\.', '\\\\', 'a.b.c') # \link{bar}
}
cat('a\tb\nc')
```
## Other formatR options
We can set **formatR** options globally:
```{r}
options(keep.blank.line=FALSE)
```
```{r demo, eval=FALSE}
```
Or locally in one chunk via `tidy.opts`. Do not keep comments:
```{r demo, eval=FALSE, tidy.opts=list(keep.comment=FALSE)}
```
Move left braces to the next line:
```{r demo, eval=2, echo=2, tidy.opts=list(left.brace.newline=TRUE)}
```
Indent by 2 spaces:
```{r demo, eval=FALSE, tidy.opts=list(reindent.spaces=2)}
```
See <http://yihui.name/formatR> for details.
## Empty chunks
```{r}
```
\documentclass{article}
\usepackage{amsmath}
\begin{document}
When the option OutDec is not \texttt{.}, put numbers in \texttt{\textbackslash{}text}. See \#348.
<<>>=
options(OutDec = ',')
@
This is the first test. abc \Sexpr{0.6} def
another test $a = \Sexpr{0.6}$.
and the last one $a = \Sexpr{'0.6'}$.
<<>>=
options(OutDec = '.')
@
This is the first test. abc \Sexpr{0.6} def
another test $a = \Sexpr{0.6}$.
and the last one $a = \Sexpr{'0.6'}$.
\end{document}
\documentclass{article}\usepackage[]{graphicx}\usepackage[]{color}
%% maxwidth is the original width if it is less than linewidth
%% otherwise use linewidth (to make sure the graphics do not exceed the margin)
\makeatletter
\def\maxwidth{ %
\ifdim\Gin@nat@width>\linewidth
\linewidth
\else
\Gin@nat@width
\fi
}
\makeatother
\definecolor{fgcolor}{rgb}{0.2, 0.2, 0.2}
\newcommand{\hlnumber}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlfunctioncall}[1]{\textcolor[rgb]{0.501960784313725,0,0.329411764705882}{\textbf{#1}}}%
\newcommand{\hlstring}[1]{\textcolor[rgb]{0.6,0.6,1}{#1}}%
\newcommand{\hlkeyword}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlargument}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlcomment}[1]{\textcolor[rgb]{0.180392156862745,0.6,0.341176470588235}{#1}}%
\newcommand{\hlroxygencomment}[1]{\textcolor[rgb]{0.43921568627451,0.47843137254902,0.701960784313725}{#1}}%
\newcommand{\hlformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hleqformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlassignement}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlpackage}[1]{\textcolor[rgb]{0.588235294117647,0.709803921568627,0.145098039215686}{#1}}%
\newcommand{\hlslot}[1]{\textit{#1}}%
\newcommand{\hlsymbol}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlprompt}[1]{\textcolor[rgb]{0.2,0.2,0.2}{#1}}%
\usepackage{framed}
\makeatletter
\newenvironment{kframe}{%
\def\at@end@of@kframe{}%
\ifinner\ifhmode%
\def\at@end@of@kframe{\end{minipage}}%
\begin{minipage}{\columnwidth}%
\fi\fi%
\def\FrameCommand##1{\hskip\@totalleftmargin \hskip-\fboxsep
\colorbox{shadecolor}{##1}\hskip-\fboxsep
% There is no \\@totalrightmargin, so:
\hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth}%
\MakeFramed {\advance\hsize-\width
\@totalleftmargin\z@ \linewidth\hsize
\@setminipage}}%
{\par\unskip\endMakeFramed%
\at@end@of@kframe}
\makeatother
\definecolor{shadecolor}{rgb}{.97, .97, .97}
\definecolor{messagecolor}{rgb}{0, 0, 0}
\definecolor{warningcolor}{rgb}{1, 0, 1}
\definecolor{errorcolor}{rgb}{1, 0, 0}
\newenvironment{knitrout}{}{} % an empty environment to be redefined in TeX
\usepackage{alltt}
\usepackage{amsmath}
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
\begin{document}
When the option OutDec is not \texttt{.}, put numbers in \texttt{\textbackslash{}text}. See \#348.
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlfunctioncall{options}(OutDec = \hlstring{","})
\end{alltt}
\end{kframe}
\end{knitrout}
This is the first test. abc \text{0,6} def
another test $a = \text{0,6}$.
and the last one $a = 0.6$.
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlfunctioncall{options}(OutDec = \hlstring{"."})
\end{alltt}
\end{kframe}
\end{knitrout}
This is the first test. abc 0.6 def
another test $a = 0.6$.
and the last one $a = 0.6$.
\end{document}

% Writing beautiful and reproducible slides quickly % Yihui Xie % 2012/04/30

Why

  • after you finished typing \documentclass{beamer} and \title{}, I have finished my first slide with markdown
  • much less commands to remember, e.g. to write bullet points, just begin with a dash "-" instead of \begin{itemize} and \item; how things can be simpler?
  • I know you want math to show you are a statistician, e.g. $f(k)={n \choose k}p^{k}(1-p)^{n-k}$
  • you do not need to maintain output -- only maintain a source file
  • HTML5/CSS3 is much more fun than LaTeX

A bit R code

head(cars)
##   speed dist
## 1     4    2
## 2     4   10
## 3     7    4
## 4     7   22
## 5     8   16
## 6     9   10
cor(cars)
##        speed   dist
## speed 1.0000 0.8069
## dist  0.8069 1.0000

Graphics too

library(ggplot2)
qplot(speed, dist, data = cars) + geom_smooth()

A scatterplot of cars

How

  • source editor: RStudio (perfect integration with knitr; one-click compilation); currently you have to use the version >= 0.96.109
  • HTML5 slides converter: pandoc; this document was generated by: pandoc -s -S -i -t dzslides --mathjax knitr-slides.md -o knitr-slides.html
  • the file knitr-slides.md is the markdown output from its source: library(knitr); knit('knitr-slides.Rmd')
  • or simple click the button Knit HTML in RStudio

For ninjas

  • you should tweak the default style; why not try some Google web fonts? (think how painful it is to wrestle with fonts in LaTeX)
  • pandoc provides 3 types of HTML5 slides (dzslides is one of them)
  • you can tweak the default template to get better appearances
  • if you have come up with a better dzslides template, please let me know or contribute to pandoc directly (e.g. pre blocks should have max-width and max-height)

For beamer lovers

  • pandoc supports conversion to beamer as well. period.

For Powerpoint lovers

  • ...

Reproducible research

It is good to include the session info, e.g. this document is produced with knitr. Here is my session info:

print(sessionInfo(), locale = FALSE)
## R version 2.15.2 (2012-10-26)
## Platform: x86_64-pc-linux-gnu (64-bit)
## 
## attached base packages:
## [1] methods   stats     graphics  grDevices utils     datasets  base     
## 
## other attached packages:
## [1] ggplot2_0.9.3 knitr_0.9.2  
## 
## loaded via a namespace (and not attached):
##  [1] colorspace_1.2-0   dichromat_1.2-4    digest_0.6.0      
##  [4] evaluate_0.4.3     formatR_0.7        grid_2.15.2       
##  [7] gtable_0.1.2       labeling_0.1       MASS_7.3-22       
## [10] munsell_0.4        plyr_1.8           proto_0.3-10      
## [13] RColorBrewer_1.0-5 reshape2_1.2.2     scales_0.2.3      
## [16] stringr_0.6.2      tools_2.15.2

Misc issues

  • the plots are too wide? use the chunk option out.width which will be used in <img width=... />, e.g. out.width=400px

Life is short

  • so keep your audience awake!

% Writing beautiful and reproducible slides quickly
% Yihui Xie
% 2012/04/30
```{r setup, include=FALSE}
# set global chunk options
opts_chunk$set(cache=TRUE)
```
# Why
- after you finished typing `\documentclass{beamer}` and `\title{}`, I have finished my first slide with markdown
- much less commands to remember, e.g. to write bullet points, just begin with a dash "`-`" instead of `\begin{itemize}` and `\item`; how things can be simpler?
- I know you want math to show you are a statistician, e.g. $f(k)={n \choose k}p^{k}(1-p)^{n-k}$
- you do not need to maintain output -- only maintain a source file
- HTML5/CSS3 is much more fun than LaTeX
# A bit R code
```{r computing}
head(cars)
cor(cars)
```
# Graphics too
```{r graphics, message=FALSE, fig.cap='A scatterplot of `cars`', fig.width=11, fig.height=5}
library(ggplot2)
qplot(speed, dist, data = cars) + geom_smooth()
```
# How
- source editor: [RStudio](http://www.rstudio.org/) (perfect integration with [**knitr**](http://yihui.name/knitr/); one-click compilation); currently you have to use the version >= 0.96.109
- HTML5 slides converter: [pandoc](http://johnmacfarlane.net/pandoc/); this document was generated by: `pandoc -s -S -i -t dzslides --mathjax knitr-slides.md -o knitr-slides.html`
- the file [`knitr-slides.md`](https://github.com/yihui/knitr-examples/blob/master/009-slides.md) is the markdown output from its [source](https://github.com/yihui/knitr-examples/blob/master/009-slides.Rmd): `library(knitr); knit('knitr-slides.Rmd')`
- or simple click the button `Knit HTML` in RStudio
# For ninjas
- you should tweak the default style; why not try some [Google web fonts](http://www.google.com/webfonts)? (think how painful it is to wrestle with fonts in LaTeX)
- pandoc provides 3 types of HTML5 slides (dzslides is one of them)
- you can tweak the default template to get better appearances
- if you have come up with a better dzslides template, please let me know or contribute to pandoc directly (e.g. `pre` blocks should have `max-width` and `max-height`)
# For beamer lovers
- pandoc supports conversion to beamer as well. period.
# For Powerpoint lovers
- ...
# Reproducible research
It is good to include the session info, e.g. this document is produced with **knitr**. Here is my session info:
```{r session-info}
print(sessionInfo(), locale=FALSE)
```
# Misc issues
- the plots are too wide? use the chunk option `out.width` which will be used in `<img width=... />`, e.g. `out.width=400px`
# Life is short
- so keep your audience awake!
![](http://i.imgur.com/qBO9K.jpg)

This is an example of using knitr with extended markdown (e.g. GFM) and uploading images to imgur.com automatically. Note you should set the graphical device to create images that can be displayed in the web browser, e.g. dev = 'png' (it is the default for markdown output) works but 'pdf' does not.

First, the input file was named as knitr-upload.Rmd (source), and knitr will automatically determine the output filename to be knitr-upload.md.

I used the code below to make sure knitr will upload images and set some global chunk options.

opts_knit$set(upload.fun = imgur_upload, base.url = NULL)  # upload all images to imgur.com
opts_chunk$set(fig.width = 5, fig.height = 5, cache = TRUE)

Now we write some code chunks in this markdown file:

## a simple calculator
1 + 1
## [1] 2
## boring random numbers
set.seed(123)
rnorm(5)
## [1] -0.56048 -0.23018  1.55871  0.07051  0.12929

We can also produce plots which are uploaded to imgur.com:

library(ggplot2)
qplot(hp, mpg, data = mtcars) + geom_smooth()

plot of chunk md-cars

ggpcp(mtcars) + geom_line()

plot of chunk md-cars

So knitr is ready with GitHub with a single markdown file.

This is an example of using **knitr** with extended markdown (e.g. [GFM](http://github.github.com/github-flavored-markdown/)) and uploading images to imgur.com automatically. Note you should set the graphical device to create images that can be displayed in the web browser, e.g. `dev = 'png'` (it is the default for markdown output) works but `'pdf'` does not.
First, the input file was named as `knitr-upload.Rmd` ([source](https://github.com/yihui/knitr-examples/blob/master/010-upload.Rmd)), and **knitr** will automatically determine the output filename to be `knitr-upload.md`.
I used the code below to make sure **knitr** will upload images and set some global chunk options.
```{r setup}
opts_knit$set(upload.fun = imgur_upload, base.url = NULL) # upload all images to imgur.com
opts_chunk$set(fig.width=5, fig.height=5, cache=TRUE)
````
Now we write some code chunks in this markdown file:
```{r}
## a simple calculator
1+1
## boring random numbers
set.seed(123)
rnorm(5)
```
We can also produce plots which are uploaded to imgur.com:
```{r md-cars, message=FALSE}
library(ggplot2)
qplot(hp, mpg, data=mtcars)+geom_smooth()
ggpcp(mtcars) + geom_line()
```
So **knitr** is ready with GitHub with a single markdown file.
\documentclass{article}
\begin{document}
<<controller>>=
# this variable controls if a chunk should be evaluated
dothis <- TRUE
@
<<chunk1, eval = dothis>>=
print('say hello world')
@
<<chunk2, eval = !dothis>>=
print('silence is gold')
@
\end{document}
\documentclass{article}\usepackage[]{graphicx}\usepackage[]{color}
%% maxwidth is the original width if it is less than linewidth
%% otherwise use linewidth (to make sure the graphics do not exceed the margin)
\makeatletter
\def\maxwidth{ %
\ifdim\Gin@nat@width>\linewidth
\linewidth
\else
\Gin@nat@width
\fi
}
\makeatother
\definecolor{fgcolor}{rgb}{0.2, 0.2, 0.2}
\newcommand{\hlnumber}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlfunctioncall}[1]{\textcolor[rgb]{0.501960784313725,0,0.329411764705882}{\textbf{#1}}}%
\newcommand{\hlstring}[1]{\textcolor[rgb]{0.6,0.6,1}{#1}}%
\newcommand{\hlkeyword}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlargument}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlcomment}[1]{\textcolor[rgb]{0.180392156862745,0.6,0.341176470588235}{#1}}%
\newcommand{\hlroxygencomment}[1]{\textcolor[rgb]{0.43921568627451,0.47843137254902,0.701960784313725}{#1}}%
\newcommand{\hlformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hleqformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlassignement}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlpackage}[1]{\textcolor[rgb]{0.588235294117647,0.709803921568627,0.145098039215686}{#1}}%
\newcommand{\hlslot}[1]{\textit{#1}}%
\newcommand{\hlsymbol}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlprompt}[1]{\textcolor[rgb]{0.2,0.2,0.2}{#1}}%
\usepackage{framed}
\makeatletter
\newenvironment{kframe}{%
\def\at@end@of@kframe{}%
\ifinner\ifhmode%
\def\at@end@of@kframe{\end{minipage}}%
\begin{minipage}{\columnwidth}%
\fi\fi%
\def\FrameCommand##1{\hskip\@totalleftmargin \hskip-\fboxsep
\colorbox{shadecolor}{##1}\hskip-\fboxsep
% There is no \\@totalrightmargin, so:
\hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth}%
\MakeFramed {\advance\hsize-\width
\@totalleftmargin\z@ \linewidth\hsize
\@setminipage}}%
{\par\unskip\endMakeFramed%
\at@end@of@kframe}
\makeatother
\definecolor{shadecolor}{rgb}{.97, .97, .97}
\definecolor{messagecolor}{rgb}{0, 0, 0}
\definecolor{warningcolor}{rgb}{1, 0, 1}
\definecolor{errorcolor}{rgb}{1, 0, 0}
\newenvironment{knitrout}{}{} % an empty environment to be redefined in TeX
\usepackage{alltt}
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
\begin{document}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlcomment{# this variable controls if a chunk should be evaluated}
dothis <- TRUE
\end{alltt}
\end{kframe}
\end{knitrout}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlfunctioncall{print}(\hlstring{"say hello world"})
\end{alltt}
\begin{verbatim}
## [1] "say hello world"
\end{verbatim}
\end{kframe}
\end{knitrout}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlfunctioncall{print}(\hlstring{"silence is gold"})
\end{alltt}
\end{kframe}
\end{knitrout}
\end{document}

This demos shows you how to replace \n to a real line break in the source.

This is what you normally see in the output:

x = "this is a long long\nstring with several\nlines"

Modify the source hook:

Now we test the source hook:

x = "this is a long long
string with several
lines"
This demos shows you how to replace `\n` to a real line break in the source.
This is what you normally see in the output:
```{r test}
x = 'this is a long long
string with several
lines'
```
Modify the `source` hook:
```{r setup, include=FALSE}
knit_hooks$set(source = function(x, options) {
paste0('\n\n```r\n', gsub('\\n', '\n', x, fixed=TRUE), '```\n\n')
})
```
Now we test the `source` hook:
```{r test2, ref.label='test'}
```
\documentclass{article}
\begin{document}
<<setup>>=
knit_hooks$set(pars = function(before, options, envir) {
if (before) do.call(graphics::par, options$pars)
})
@
Then this function will be called for a chunk like this:
% pass a list of graphics parameters to par()
<<myplot, pars=list(mar = c(4, 4, .1, .1))>>=
hist(rnorm(100), main = '') # no main title
@
\end{document}
\documentclass{article}\usepackage[]{graphicx}\usepackage[]{color}
%% maxwidth is the original width if it is less than linewidth
%% otherwise use linewidth (to make sure the graphics do not exceed the margin)
\makeatletter
\def\maxwidth{ %
\ifdim\Gin@nat@width>\linewidth
\linewidth
\else
\Gin@nat@width
\fi
}
\makeatother
\definecolor{fgcolor}{rgb}{0.2, 0.2, 0.2}
\newcommand{\hlnumber}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlfunctioncall}[1]{\textcolor[rgb]{0.501960784313725,0,0.329411764705882}{\textbf{#1}}}%
\newcommand{\hlstring}[1]{\textcolor[rgb]{0.6,0.6,1}{#1}}%
\newcommand{\hlkeyword}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlargument}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlcomment}[1]{\textcolor[rgb]{0.180392156862745,0.6,0.341176470588235}{#1}}%
\newcommand{\hlroxygencomment}[1]{\textcolor[rgb]{0.43921568627451,0.47843137254902,0.701960784313725}{#1}}%
\newcommand{\hlformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hleqformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlassignement}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlpackage}[1]{\textcolor[rgb]{0.588235294117647,0.709803921568627,0.145098039215686}{#1}}%
\newcommand{\hlslot}[1]{\textit{#1}}%
\newcommand{\hlsymbol}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlprompt}[1]{\textcolor[rgb]{0.2,0.2,0.2}{#1}}%
\usepackage{framed}
\makeatletter
\newenvironment{kframe}{%
\def\at@end@of@kframe{}%
\ifinner\ifhmode%
\def\at@end@of@kframe{\end{minipage}}%
\begin{minipage}{\columnwidth}%
\fi\fi%
\def\FrameCommand##1{\hskip\@totalleftmargin \hskip-\fboxsep
\colorbox{shadecolor}{##1}\hskip-\fboxsep
% There is no \\@totalrightmargin, so:
\hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth}%
\MakeFramed {\advance\hsize-\width
\@totalleftmargin\z@ \linewidth\hsize
\@setminipage}}%
{\par\unskip\endMakeFramed%
\at@end@of@kframe}
\makeatother
\definecolor{shadecolor}{rgb}{.97, .97, .97}
\definecolor{messagecolor}{rgb}{0, 0, 0}
\definecolor{warningcolor}{rgb}{1, 0, 1}
\definecolor{errorcolor}{rgb}{1, 0, 0}
\newenvironment{knitrout}{}{} % an empty environment to be redefined in TeX
\usepackage{alltt}
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
\begin{document}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
knit_hooks$\hlfunctioncall{set}(pars = \hlfunctioncall{function}(before, options, envir) \{
\hlfunctioncall{if} (before)
\hlfunctioncall{do.call}(graphics::par, options$pars)
\})
\end{alltt}
\end{kframe}
\end{knitrout}
Then this function will be called for a chunk like this:
% pass a list of graphics parameters to par()
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlfunctioncall{hist}(\hlfunctioncall{rnorm}(100), main = \hlstring{""}) # no main title
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/013-par-myplot}
\end{knitrout}
\end{document}
\documentclass{article}
\begin{document}
This is all you need to do if you want to go back to the Sweave style:
<<setup, include=FALSE>>=
render_sweave()
@
The quick brown fox jumps over the lazy dog the quick brown fox jumps over the
lazy dog the quick brown fox jumps over the lazy dog.
<<test>>=
1+1
rnorm(30)
@
The quick brown fox jumps over the lazy dog the quick brown fox jumps over the
lazy dog the quick brown fox jumps over the lazy dog.
\end{document}
\documentclass{article}\usepackage[]{graphicx}\usepackage[]{color}
%% maxwidth is the original width if it is less than linewidth
%% otherwise use linewidth (to make sure the graphics do not exceed the margin)
\makeatletter
\def\maxwidth{ %
\ifdim\Gin@nat@width>\linewidth
\linewidth
\else
\Gin@nat@width
\fi
}
\makeatother
\usepackage{Sweave}
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
\begin{document}
This is all you need to do if you want to go back to the Sweave style:
The quick brown fox jumps over the lazy dog the quick brown fox jumps over the
lazy dog the quick brown fox jumps over the lazy dog.
\begin{Schunk}
\begin{Sinput}
> 1 + 1
\end{Sinput}
\begin{Soutput}
[1] 2
\end{Soutput}
\begin{Sinput}
> rnorm(30)
\end{Sinput}
\begin{Soutput}
[1] -0.56048 -0.23018 1.55871 0.07051 0.12929 1.71506 0.46092
[8] -1.26506 -0.68685 -0.44566 1.22408 0.35981 0.40077 0.11068
[15] -0.55584 1.78691 0.49785 -1.96662 0.70136 -0.47279 -1.06782
[22] -0.21797 -1.02600 -0.72889 -0.62504 -1.68669 0.83779 0.15337
[29] -1.13814 1.25381
\end{Soutput}
\end{Schunk}
The quick brown fox jumps over the lazy dog the quick brown fox jumps over the
lazy dog the quick brown fox jumps over the lazy dog.
\end{document}
\documentclass{article}
\begin{document}
This is all you need to do if you want to use the listings package:
<<setup, include=FALSE>>=
render_listings()
@
The quick brown fox jumps over the lazy dog the quick brown fox jumps over the
lazy dog the quick brown fox jumps over the lazy dog.
<<test>>=
1+1
rnorm(30)
@
The quick brown fox jumps over the lazy dog the quick brown fox jumps over the
lazy dog the quick brown fox jumps over the lazy dog.
\end{document}
\documentclass{article}\usepackage[]{graphicx}\usepackage[]{color}
%% maxwidth is the original width if it is less than linewidth
%% otherwise use linewidth (to make sure the graphics do not exceed the margin)
\makeatletter
\def\maxwidth{ %
\ifdim\Gin@nat@width>\linewidth
\linewidth
\else
\Gin@nat@width
\fi
}
\makeatother
\usepackage{Sweavel}
\begin{document}
This is all you need to do if you want to use the listings package:
The quick brown fox jumps over the lazy dog the quick brown fox jumps over the
lazy dog the quick brown fox jumps over the lazy dog.
\begin{Schunk}
\begin{Sinput}
1 + 1
\end{Sinput}
\begin{Soutput}
[1] 2
\end{Soutput}
\begin{Sinput}
rnorm(30)
\end{Sinput}
\begin{Soutput}
[1] -0.56048 -0.23018 1.55871 0.07051 0.12929 1.71506 0.46092
[8] -1.26506 -0.68685 -0.44566 1.22408 0.35981 0.40077 0.11068
[15] -0.55584 1.78691 0.49785 -1.96662 0.70136 -0.47279 -1.06782
[22] -0.21797 -1.02600 -0.72889 -0.62504 -1.68669 0.83779 0.15337
[29] -1.13814 1.25381
\end{Soutput}
\end{Schunk}
The quick brown fox jumps over the lazy dog the quick brown fox jumps over the
lazy dog the quick brown fox jumps over the lazy dog.
\end{document}
\documentclass{article}
\begin{document}
This demo shows you how to use the Palatino font in the Cairo PDF device.
<<dev-args, dev='cairo_pdf', dev.args=list(family='Palatino'), fig.width=4.5, fig.height=3>>=
plot(1, main='Hello, Palatino', xlab='This is x-axis', ylab='This is y-axis')
@
You can also pass other arguments to the device.
\end{document}
\documentclass{article}\usepackage[]{graphicx}\usepackage[]{color}
%% maxwidth is the original width if it is less than linewidth
%% otherwise use linewidth (to make sure the graphics do not exceed the margin)
\makeatletter
\def\maxwidth{ %
\ifdim\Gin@nat@width>\linewidth
\linewidth
\else
\Gin@nat@width
\fi
}
\makeatother
\definecolor{fgcolor}{rgb}{0.2, 0.2, 0.2}
\newcommand{\hlnumber}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlfunctioncall}[1]{\textcolor[rgb]{0.501960784313725,0,0.329411764705882}{\textbf{#1}}}%
\newcommand{\hlstring}[1]{\textcolor[rgb]{0.6,0.6,1}{#1}}%
\newcommand{\hlkeyword}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlargument}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlcomment}[1]{\textcolor[rgb]{0.180392156862745,0.6,0.341176470588235}{#1}}%
\newcommand{\hlroxygencomment}[1]{\textcolor[rgb]{0.43921568627451,0.47843137254902,0.701960784313725}{#1}}%
\newcommand{\hlformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hleqformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlassignement}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlpackage}[1]{\textcolor[rgb]{0.588235294117647,0.709803921568627,0.145098039215686}{#1}}%
\newcommand{\hlslot}[1]{\textit{#1}}%
\newcommand{\hlsymbol}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlprompt}[1]{\textcolor[rgb]{0.2,0.2,0.2}{#1}}%
\usepackage{framed}
\makeatletter
\newenvironment{kframe}{%
\def\at@end@of@kframe{}%
\ifinner\ifhmode%
\def\at@end@of@kframe{\end{minipage}}%
\begin{minipage}{\columnwidth}%
\fi\fi%
\def\FrameCommand##1{\hskip\@totalleftmargin \hskip-\fboxsep
\colorbox{shadecolor}{##1}\hskip-\fboxsep
% There is no \\@totalrightmargin, so:
\hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth}%
\MakeFramed {\advance\hsize-\width
\@totalleftmargin\z@ \linewidth\hsize
\@setminipage}}%
{\par\unskip\endMakeFramed%
\at@end@of@kframe}
\makeatother
\definecolor{shadecolor}{rgb}{.97, .97, .97}
\definecolor{messagecolor}{rgb}{0, 0, 0}
\definecolor{warningcolor}{rgb}{1, 0, 1}
\definecolor{errorcolor}{rgb}{1, 0, 0}
\newenvironment{knitrout}{}{} % an empty environment to be redefined in TeX
\usepackage{alltt}
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
\begin{document}
This demo shows you how to use the Palatino font in the Cairo PDF device.
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlfunctioncall{plot}(1, main = \hlstring{"Hello, Palatino"}, xlab = \hlstring{"This is x-axis"}, ylab = \hlstring{"This is y-axis"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/016-device-dev-args}
\end{knitrout}
You can also pass other arguments to the device.
\end{document}
\documentclass{article}
\begin{document}
<<setup, cache=FALSE>>=
# global chunk options
opts_chunk$set(cache=TRUE, autodep=TRUE)
dep_auto() # figure out dependencies automatically
@
We create a new global object \texttt{x} in the first chunk (a):
<<a>>=
x = 5
@
Then we print it in the second chunk (b). Because we have used
\emph{build\_dep()} in the first chunk, \textbf{knitr} should be able to
figure out that chunk b depends on chunk a.
<<b>>=
(y = x + 2)
@
You can verify it by changing chunk a to see if b also changes.
\end{document}
\documentclass{article}\usepackage[]{graphicx}\usepackage[]{color}
%% maxwidth is the original width if it is less than linewidth
%% otherwise use linewidth (to make sure the graphics do not exceed the margin)
\makeatletter
\def\maxwidth{ %
\ifdim\Gin@nat@width>\linewidth
\linewidth
\else
\Gin@nat@width
\fi
}
\makeatother
\definecolor{fgcolor}{rgb}{0.2, 0.2, 0.2}
\newcommand{\hlnumber}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlfunctioncall}[1]{\textcolor[rgb]{0.501960784313725,0,0.329411764705882}{\textbf{#1}}}%
\newcommand{\hlstring}[1]{\textcolor[rgb]{0.6,0.6,1}{#1}}%
\newcommand{\hlkeyword}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlargument}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlcomment}[1]{\textcolor[rgb]{0.180392156862745,0.6,0.341176470588235}{#1}}%
\newcommand{\hlroxygencomment}[1]{\textcolor[rgb]{0.43921568627451,0.47843137254902,0.701960784313725}{#1}}%
\newcommand{\hlformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hleqformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlassignement}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlpackage}[1]{\textcolor[rgb]{0.588235294117647,0.709803921568627,0.145098039215686}{#1}}%
\newcommand{\hlslot}[1]{\textit{#1}}%
\newcommand{\hlsymbol}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlprompt}[1]{\textcolor[rgb]{0.2,0.2,0.2}{#1}}%
\usepackage{framed}
\makeatletter
\newenvironment{kframe}{%
\def\at@end@of@kframe{}%
\ifinner\ifhmode%
\def\at@end@of@kframe{\end{minipage}}%
\begin{minipage}{\columnwidth}%
\fi\fi%
\def\FrameCommand##1{\hskip\@totalleftmargin \hskip-\fboxsep
\colorbox{shadecolor}{##1}\hskip-\fboxsep
% There is no \\@totalrightmargin, so:
\hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth}%
\MakeFramed {\advance\hsize-\width
\@totalleftmargin\z@ \linewidth\hsize
\@setminipage}}%
{\par\unskip\endMakeFramed%
\at@end@of@kframe}
\makeatother
\definecolor{shadecolor}{rgb}{.97, .97, .97}
\definecolor{messagecolor}{rgb}{0, 0, 0}
\definecolor{warningcolor}{rgb}{1, 0, 1}
\definecolor{errorcolor}{rgb}{1, 0, 0}
\newenvironment{knitrout}{}{} % an empty environment to be redefined in TeX
\usepackage{alltt}
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
\begin{document}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlcomment{# global chunk options}
opts_chunk$\hlfunctioncall{set}(cache = TRUE, autodep = TRUE)
\hlfunctioncall{dep_auto}() \hlcomment{# figure out dependencies automatically}
\end{alltt}
\end{kframe}
\end{knitrout}
We create a new global object \texttt{x} in the first chunk (a):
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
x = 5
\end{alltt}
\end{kframe}
\end{knitrout}
Then we print it in the second chunk (b). Because we have used
\emph{build\_dep()} in the first chunk, \textbf{knitr} should be able to
figure out that chunk b depends on chunk a.
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
(y = x + 2)
\end{alltt}
\begin{verbatim}
## [1] 7
\end{verbatim}
\end{kframe}
\end{knitrout}
You can verify it by changing chunk a to see if b also changes.
\end{document}
\documentclass{beamer}
\usepackage{url}
\begin{document}
\title{Filling a full beamer slide with tikzDevice output from R}
\author{Yihui Xie}
\maketitle
<<setup, include=FALSE>>=
options(width = 65)
# smaller font size for chunks
opts_chunk$set(size = 'footnotesize', background='white', cache=TRUE)
@
\begin{frame}[fragile]
\frametitle{A frame with the fragile option}
<<boring-random>>=
set.seed(1121)
(x=rnorm(20))
mean(x);var(x)
@
\end{frame}
\begin{frame}
<<boring-plots, echo=FALSE, dev='tikz', fig.width=4.4, fig.height=3.3, out.width='.9\\paperwidth'>>=
par(mar = c(4.5, 4, .1, .1))
hist(x, main='', xlab='$x$ (how the fonts look like here?)',
ylab='$\\hat{f}(x) = \\frac{1}{nh}\\sum_{i=1}^n \\cdots$')
@
\end{frame}
\end{document}
\documentclass{beamer}\usepackage[]{graphicx}\usepackage[]{color}
%% maxwidth is the original width if it is less than linewidth
%% otherwise use linewidth (to make sure the graphics do not exceed the margin)
\makeatletter
\def\maxwidth{ %
\ifdim\Gin@nat@width>\linewidth
\linewidth
\else
\Gin@nat@width
\fi
}
\makeatother
\definecolor{fgcolor}{rgb}{0.2, 0.2, 0.2}
\newcommand{\hlnumber}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlfunctioncall}[1]{\textcolor[rgb]{0.501960784313725,0,0.329411764705882}{\textbf{#1}}}%
\newcommand{\hlstring}[1]{\textcolor[rgb]{0.6,0.6,1}{#1}}%
\newcommand{\hlkeyword}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlargument}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlcomment}[1]{\textcolor[rgb]{0.180392156862745,0.6,0.341176470588235}{#1}}%
\newcommand{\hlroxygencomment}[1]{\textcolor[rgb]{0.43921568627451,0.47843137254902,0.701960784313725}{#1}}%
\newcommand{\hlformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hleqformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlassignement}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlpackage}[1]{\textcolor[rgb]{0.588235294117647,0.709803921568627,0.145098039215686}{#1}}%
\newcommand{\hlslot}[1]{\textit{#1}}%
\newcommand{\hlsymbol}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlprompt}[1]{\textcolor[rgb]{0.2,0.2,0.2}{#1}}%
\usepackage{framed}
\makeatletter
\newenvironment{kframe}{%
\def\at@end@of@kframe{}%
\ifinner\ifhmode%
\def\at@end@of@kframe{\end{minipage}}%
\begin{minipage}{\columnwidth}%
\fi\fi%
\def\FrameCommand##1{\hskip\@totalleftmargin \hskip-\fboxsep
\colorbox{shadecolor}{##1}\hskip-\fboxsep
% There is no \\@totalrightmargin, so:
\hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth}%
\MakeFramed {\advance\hsize-\width
\@totalleftmargin\z@ \linewidth\hsize
\@setminipage}}%
{\par\unskip\endMakeFramed%
\at@end@of@kframe}
\makeatother
\definecolor{shadecolor}{rgb}{.97, .97, .97}
\definecolor{messagecolor}{rgb}{0, 0, 0}
\definecolor{warningcolor}{rgb}{1, 0, 1}
\definecolor{errorcolor}{rgb}{1, 0, 0}
\newenvironment{knitrout}{}{} % an empty environment to be redefined in TeX
\usepackage{alltt}
\usepackage{url}
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
\begin{document}
\title{Filling a full beamer slide with tikzDevice output from R}
\author{Yihui Xie}
\maketitle
\begin{frame}[fragile]
\frametitle{A frame with the fragile option}
\begin{knitrout}\footnotesize
\definecolor{shadecolor}{rgb}{1, 1, 1}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlfunctioncall{set.seed}(1121)
(x = \hlfunctioncall{rnorm}(20))
\end{alltt}
\begin{verbatim}
## [1] 0.14496 0.43832 0.15319 1.08494 1.99954 -0.81188
## [7] 0.16027 0.58589 0.36009 -0.02531 0.15088 0.11008
## [13] 1.35968 -0.32699 -0.71638 1.80977 0.50840 -0.52746
## [19] 0.13272 -0.15594
\end{verbatim}
\begin{alltt}
\hlfunctioncall{mean}(x)
\end{alltt}
\begin{verbatim}
## [1] 0.3217
\end{verbatim}
\begin{alltt}
\hlfunctioncall{var}(x)
\end{alltt}
\begin{verbatim}
## [1] 0.5715
\end{verbatim}
\end{kframe}
\end{knitrout}
\end{frame}
\begin{frame}
\begin{knitrout}\footnotesize
\definecolor{shadecolor}{rgb}{1, 1, 1}\color{fgcolor}
\includegraphics[width=.9\paperwidth]{figure/018-fullfig-tikz-boring-plots}
\end{knitrout}
\end{frame}
\end{document}
\documentclass{article}
\begin{document}
Knitr can automatically generate a figure environment if fig.cap is specified.
<<test, fig.cap=paste('$2 \\times 2$ is', 2*2), fig.height=2.5>>=
par(mar=c(4, 4, .1, .1)); plot(runif(4))
@
When fig.cap needs to use objects in the current chunk, we need to set the eval.after options so the objects are available when fig.cap is used.
<<setup>>=
# evaluate fig.cap after a chunk is evaluated
opts_knit$set(eval.after = 'fig.cap')
@
Dynamically generate a figure caption:
<<t-test, fig.cap=paste('The P-value is', format.pval(t.test(x)$p.value)), fig.height=2.5>>=
x = rnorm(30)
par(mar=c(4, 4, .1, .1)); hist(x, main='')
@
Change the figure environment:
<<figure-asterisk, fig.env='figure*', fig.cap='Figure * environment.', fig.width=2, fig.height=4>>=
par(mar=c(4, 4, .1, .1)); boxplot(x)
@
If you have two figures, you can assign two captions to fig.cap:
<<two-caps, fig.cap=c('Hi figure one', 'Hi figure two'), fig.width=2, fig.height=1.5, fig.align='center'>>=
par(mar=rep(0, 4), ann=FALSE)
plot(1:10)
plot(runif(10))
@
You can use figure references too. For example, Figure \ref{fig:t-test} is a histogram, and Figure \ref{fig:figure-asterisk} is a boxplot. The reference key is ``fig: + the chunk label'' by default.
\end{document}
\documentclass{article}\usepackage[]{graphicx}\usepackage[]{color}
%% maxwidth is the original width if it is less than linewidth
%% otherwise use linewidth (to make sure the graphics do not exceed the margin)
\makeatletter
\def\maxwidth{ %
\ifdim\Gin@nat@width>\linewidth
\linewidth
\else
\Gin@nat@width
\fi
}
\makeatother
\definecolor{fgcolor}{rgb}{0.2, 0.2, 0.2}
\newcommand{\hlnumber}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlfunctioncall}[1]{\textcolor[rgb]{0.501960784313725,0,0.329411764705882}{\textbf{#1}}}%
\newcommand{\hlstring}[1]{\textcolor[rgb]{0.6,0.6,1}{#1}}%
\newcommand{\hlkeyword}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlargument}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlcomment}[1]{\textcolor[rgb]{0.180392156862745,0.6,0.341176470588235}{#1}}%
\newcommand{\hlroxygencomment}[1]{\textcolor[rgb]{0.43921568627451,0.47843137254902,0.701960784313725}{#1}}%
\newcommand{\hlformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hleqformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlassignement}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlpackage}[1]{\textcolor[rgb]{0.588235294117647,0.709803921568627,0.145098039215686}{#1}}%
\newcommand{\hlslot}[1]{\textit{#1}}%
\newcommand{\hlsymbol}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlprompt}[1]{\textcolor[rgb]{0.2,0.2,0.2}{#1}}%
\usepackage{framed}
\makeatletter
\newenvironment{kframe}{%
\def\at@end@of@kframe{}%
\ifinner\ifhmode%
\def\at@end@of@kframe{\end{minipage}}%
\begin{minipage}{\columnwidth}%
\fi\fi%
\def\FrameCommand##1{\hskip\@totalleftmargin \hskip-\fboxsep
\colorbox{shadecolor}{##1}\hskip-\fboxsep
% There is no \\@totalrightmargin, so:
\hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth}%
\MakeFramed {\advance\hsize-\width
\@totalleftmargin\z@ \linewidth\hsize
\@setminipage}}%
{\par\unskip\endMakeFramed%
\at@end@of@kframe}
\makeatother
\definecolor{shadecolor}{rgb}{.97, .97, .97}
\definecolor{messagecolor}{rgb}{0, 0, 0}
\definecolor{warningcolor}{rgb}{1, 0, 1}
\definecolor{errorcolor}{rgb}{1, 0, 0}
\newenvironment{knitrout}{}{} % an empty environment to be redefined in TeX
\usepackage{alltt}
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
\begin{document}
Knitr can automatically generate a figure environment if fig.cap is specified.
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlfunctioncall{par}(mar = \hlfunctioncall{c}(4, 4, 0.1, 0.1))
\hlfunctioncall{plot}(\hlfunctioncall{runif}(4))
\end{alltt}
\end{kframe}\begin{figure}[]
\includegraphics[width=\maxwidth]{figure/019-fig-caption-test} \caption[$2 \times 2$ is 4]{$2 \times 2$ is 4\label{fig:test}}
\end{figure}
\end{knitrout}
When fig.cap needs to use objects in the current chunk, we need to set the eval.after options so the objects are available when fig.cap is used.
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlcomment{# evaluate fig.cap after a chunk is evaluated}
opts_knit$\hlfunctioncall{set}(eval.after = \hlstring{"fig.cap"})
\end{alltt}
\end{kframe}
\end{knitrout}
Dynamically generate a figure caption:
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
x = \hlfunctioncall{rnorm}(30)
\hlfunctioncall{par}(mar = \hlfunctioncall{c}(4, 4, 0.1, 0.1))
\hlfunctioncall{hist}(x, main = \hlstring{""})
\end{alltt}
\end{kframe}\begin{figure}[]
\includegraphics[width=\maxwidth]{figure/019-fig-caption-t-test} \caption[The P-value is 0]{The P-value is 0.93\label{fig:t-test}}
\end{figure}
\end{knitrout}
Change the figure environment:
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlfunctioncall{par}(mar = \hlfunctioncall{c}(4, 4, 0.1, 0.1))
\hlfunctioncall{boxplot}(x)
\end{alltt}
\end{kframe}\begin{figure*}[]
\includegraphics[width=\maxwidth]{figure/019-fig-caption-figure-asterisk} \caption[Figure * environment]{Figure * environment.\label{fig:figure-asterisk}}
\end{figure*}
\end{knitrout}
If you have two figures, you can assign two captions to fig.cap:
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlfunctioncall{par}(mar = \hlfunctioncall{rep}(0, 4), ann = FALSE)
\hlfunctioncall{plot}(1:10)
\end{alltt}
\end{kframe}\begin{figure}[]
{\centering \includegraphics[width=\maxwidth]{figure/019-fig-caption-two-caps1}
}
\caption[Hi figure one]{Hi figure one\label{fig:two-caps1}}
\end{figure}
\begin{kframe}\begin{alltt}
\hlfunctioncall{plot}(\hlfunctioncall{runif}(10))
\end{alltt}
\end{kframe}\begin{figure}[]
{\centering \includegraphics[width=\maxwidth]{figure/019-fig-caption-two-caps2}
}
\caption[Hi figure two]{Hi figure two\label{fig:two-caps2}}
\end{figure}
\end{knitrout}
You can use figure references too. For example, Figure \ref{fig:t-test} is a histogram, and Figure \ref{fig:figure-asterisk} is a boxplot. The reference key is ``fig: + the chunk label'' by default.
\end{document}
\documentclass{article}
\begin{document}
Collect results from the template for each i and write them back later.
<<run-all, include=FALSE>>=
out = NULL
for (i in 1:3) {
out = c(out, knit_child('020-for-template.rnw'))
}
@
\Sexpr{paste(out, collapse = '\n')}
\end{document}
\documentclass{article}\usepackage[]{graphicx}\usepackage[]{color}
%% maxwidth is the original width if it is less than linewidth
%% otherwise use linewidth (to make sure the graphics do not exceed the margin)
\makeatletter
\def\maxwidth{ %
\ifdim\Gin@nat@width>\linewidth
\linewidth
\else
\Gin@nat@width
\fi
}
\makeatother
\definecolor{fgcolor}{rgb}{0.2, 0.2, 0.2}
\newcommand{\hlnumber}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlfunctioncall}[1]{\textcolor[rgb]{0.501960784313725,0,0.329411764705882}{\textbf{#1}}}%
\newcommand{\hlstring}[1]{\textcolor[rgb]{0.6,0.6,1}{#1}}%
\newcommand{\hlkeyword}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlargument}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlcomment}[1]{\textcolor[rgb]{0.180392156862745,0.6,0.341176470588235}{#1}}%
\newcommand{\hlroxygencomment}[1]{\textcolor[rgb]{0.43921568627451,0.47843137254902,0.701960784313725}{#1}}%
\newcommand{\hlformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hleqformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlassignement}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlpackage}[1]{\textcolor[rgb]{0.588235294117647,0.709803921568627,0.145098039215686}{#1}}%
\newcommand{\hlslot}[1]{\textit{#1}}%
\newcommand{\hlsymbol}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlprompt}[1]{\textcolor[rgb]{0.2,0.2,0.2}{#1}}%
\usepackage{framed}
\makeatletter
\newenvironment{kframe}{%
\def\at@end@of@kframe{}%
\ifinner\ifhmode%
\def\at@end@of@kframe{\end{minipage}}%
\begin{minipage}{\columnwidth}%
\fi\fi%
\def\FrameCommand##1{\hskip\@totalleftmargin \hskip-\fboxsep
\colorbox{shadecolor}{##1}\hskip-\fboxsep
% There is no \\@totalrightmargin, so:
\hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth}%
\MakeFramed {\advance\hsize-\width
\@totalleftmargin\z@ \linewidth\hsize
\@setminipage}}%
{\par\unskip\endMakeFramed%
\at@end@of@kframe}
\makeatother
\definecolor{shadecolor}{rgb}{.97, .97, .97}
\definecolor{messagecolor}{rgb}{0, 0, 0}
\definecolor{warningcolor}{rgb}{1, 0, 1}
\definecolor{errorcolor}{rgb}{1, 0, 0}
\newenvironment{knitrout}{}{} % an empty environment to be redefined in TeX
\usepackage{alltt}
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
\begin{document}
Collect results from the template for each i and write them back later.
\section{Now i is 1}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlfunctioncall{print}(i)
\end{alltt}
\begin{verbatim}
## [1] 1
\end{verbatim}
\begin{alltt}
iris[i, ]
\end{alltt}
\begin{verbatim}
## Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1 5.1 3.5 1.4 0.2 setosa
\end{verbatim}
\end{kframe}
\end{knitrout}
\section{Now i is 2}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlfunctioncall{print}(i)
\end{alltt}
\begin{verbatim}
## [1] 2
\end{verbatim}
\begin{alltt}
iris[i, ]
\end{alltt}
\begin{verbatim}
## Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 2 4.9 3 1.4 0.2 setosa
\end{verbatim}
\end{kframe}
\end{knitrout}
\section{Now i is 3}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlfunctioncall{print}(i)
\end{alltt}
\begin{verbatim}
## [1] 3
\end{verbatim}
\begin{alltt}
iris[i, ]
\end{alltt}
\begin{verbatim}
## Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 3 4.7 3.2 1.3 0.2 setosa
\end{verbatim}
\end{kframe}
\end{knitrout}
\end{document}
\section{Now i is \Sexpr{i}}
<<>>=
print(i)
iris[i, ]
@
\documentclass[a4paper,titlepage]{tufte-handout}
\title{ggplot2 Gallery}
\begin{document}
\maketitle
\tableofcontents
<<setup, include=FALSE>>=
# cache chunks and do not tidy ggplot2 examples code
opts_chunk$set(tidy = FALSE, cache = TRUE)
@
% all geoms in ggplot2
<<write-examples, include=FALSE>>=
library(ggplot2)
ex = lapply(apropos("^geom_"), function(g) {
p = utils:::index.search(g, find.package(), TRUE)
tools::Rd2ex(utils:::.getHelpFile(p), f <- tempfile())
c(sprintf("\\section{%s}\n\n<<%s>>=",
knitr:::escape_latex(g), g),
readLines(f), "@\n\n")
})
@
\Sexpr{knit(text = unlist(ex))}
\end{document}
\documentclass[a4paper,titlepage]{tufte-handout}\usepackage[]{graphicx}\usepackage[]{color}
%% maxwidth is the original width if it is less than linewidth
%% otherwise use linewidth (to make sure the graphics do not exceed the margin)
\makeatletter
\def\maxwidth{ %
\ifdim\Gin@nat@width>\linewidth
\linewidth
\else
\Gin@nat@width
\fi
}
\makeatother
\definecolor{fgcolor}{rgb}{0.2, 0.2, 0.2}
\newcommand{\hlnumber}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlfunctioncall}[1]{\textcolor[rgb]{0.501960784313725,0,0.329411764705882}{\textbf{#1}}}%
\newcommand{\hlstring}[1]{\textcolor[rgb]{0.6,0.6,1}{#1}}%
\newcommand{\hlkeyword}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlargument}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlcomment}[1]{\textcolor[rgb]{0.180392156862745,0.6,0.341176470588235}{#1}}%
\newcommand{\hlroxygencomment}[1]{\textcolor[rgb]{0.43921568627451,0.47843137254902,0.701960784313725}{#1}}%
\newcommand{\hlformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hleqformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlassignement}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlpackage}[1]{\textcolor[rgb]{0.588235294117647,0.709803921568627,0.145098039215686}{#1}}%
\newcommand{\hlslot}[1]{\textit{#1}}%
\newcommand{\hlsymbol}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlprompt}[1]{\textcolor[rgb]{0.2,0.2,0.2}{#1}}%
\usepackage{framed}
\makeatletter
\newenvironment{kframe}{%
\def\at@end@of@kframe{}%
\ifinner\ifhmode%
\def\at@end@of@kframe{\end{minipage}}%
\begin{minipage}{\columnwidth}%
\fi\fi%
\def\FrameCommand##1{\hskip\@totalleftmargin \hskip-\fboxsep
\colorbox{shadecolor}{##1}\hskip-\fboxsep
% There is no \\@totalrightmargin, so:
\hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth}%
\MakeFramed {\advance\hsize-\width
\@totalleftmargin\z@ \linewidth\hsize
\@setminipage}}%
{\par\unskip\endMakeFramed%
\at@end@of@kframe}
\makeatother
\definecolor{shadecolor}{rgb}{.97, .97, .97}
\definecolor{messagecolor}{rgb}{0, 0, 0}
\definecolor{warningcolor}{rgb}{1, 0, 1}
\definecolor{errorcolor}{rgb}{1, 0, 0}
\newenvironment{knitrout}{}{} % an empty environment to be redefined in TeX
\usepackage{alltt}
\title{ggplot2 Gallery}
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
\begin{document}
\maketitle
\tableofcontents
% all geoms in ggplot2
\section{geom\_abline}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlcomment{### Name: geom_abline}
\hlcomment{### Title: Line specified by slope and intercept.}
\hlcomment{### Aliases: geom_abline}
\hlcomment{### ** Examples}
p <- \hlfunctioncall{qplot}(wt, mpg, data = mtcars)
\hlcomment{# Fixed slopes and intercepts}
p + \hlfunctioncall{geom_abline}() \hlcomment{# Can't see it - outside the range of the data}
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_abline1}
\begin{kframe}\begin{alltt}
p + \hlfunctioncall{geom_abline}(intercept = 20)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_abline2}
\begin{kframe}\begin{alltt}
\hlcomment{# Calculate slope and intercept of line of best fit}
\hlfunctioncall{coef}(\hlfunctioncall{lm}(mpg ~ wt, data = mtcars))
\end{alltt}
\begin{verbatim}
## (Intercept) wt
## 37.285 -5.344
\end{verbatim}
\begin{alltt}
p + \hlfunctioncall{geom_abline}(intercept = 37, slope = -5)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_abline3}
\begin{kframe}\begin{alltt}
p + \hlfunctioncall{geom_abline}(intercept = 10, colour = \hlstring{"red"}, size = 2)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_abline4}
\begin{kframe}\begin{alltt}
\hlcomment{# See ?stat_smooth for fitting smooth models to data}
p + \hlfunctioncall{stat_smooth}(method=\hlstring{"lm"}, se=FALSE)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_abline5}
\begin{kframe}\begin{alltt}
\hlcomment{# Slopes and intercepts as data}
p <- \hlfunctioncall{ggplot}(mtcars, \hlfunctioncall{aes}(x = wt, y=mpg), . ~ cyl) + \hlfunctioncall{geom_point}()
df <- \hlfunctioncall{data.frame}(a=\hlfunctioncall{rnorm}(10, 25), b=\hlfunctioncall{rnorm}(10, 0))
p + \hlfunctioncall{geom_abline}(\hlfunctioncall{aes}(intercept=a, slope=b), data=df)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_abline6}
\begin{kframe}\begin{alltt}
\hlcomment{# Slopes and intercepts from linear model}
\hlfunctioncall{library}(plyr)
coefs <- \hlfunctioncall{ddply}(mtcars, \hlfunctioncall{.}(cyl), \hlfunctioncall{function}(df) \{
m <- \hlfunctioncall{lm}(mpg ~ wt, data=df)
\hlfunctioncall{data.frame}(a = \hlfunctioncall{coef}(m)[1], b = \hlfunctioncall{coef}(m)[2])
\})
\hlfunctioncall{str}(coefs)
\end{alltt}
\begin{verbatim}
## 'data.frame': 3 obs. of 3 variables:
## $ cyl: num 4 6 8
## $ a : num 39.6 28.4 23.9
## $ b : num -5.65 -2.78 -2.19
\end{verbatim}
\begin{alltt}
p + \hlfunctioncall{geom_abline}(data=coefs, \hlfunctioncall{aes}(intercept=a, slope=b))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_abline7}
\begin{kframe}\begin{alltt}
\hlcomment{# It's actually a bit easier to do this with stat_smooth}
p + \hlfunctioncall{geom_smooth}(\hlfunctioncall{aes}(group=cyl), method=\hlstring{"lm"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_abline8}
\begin{kframe}\begin{alltt}
p + \hlfunctioncall{geom_smooth}(\hlfunctioncall{aes}(group=cyl), method=\hlstring{"lm"}, fullrange=TRUE)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_abline9}
\begin{kframe}\begin{alltt}
\hlcomment{# With coordinate transforms}
p + \hlfunctioncall{geom_abline}(intercept = 37, slope = -5) + \hlfunctioncall{coord_flip}()
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_abline10}
\begin{kframe}\begin{alltt}
p + \hlfunctioncall{geom_abline}(intercept = 37, slope = -5) + \hlfunctioncall{coord_polar}()
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_abline11}
\begin{kframe}\begin{alltt}
\end{alltt}
\end{kframe}
\end{knitrout}
\section{geom\_area}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlcomment{### Name: geom_area}
\hlcomment{### Title: Area plot.}
\hlcomment{### Aliases: geom_area}
\hlcomment{### ** Examples}
\hlcomment{# see geom_ribbon}
\end{alltt}
\end{kframe}
\end{knitrout}
\section{geom\_bar}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlcomment{### Name: geom_bar}
\hlcomment{### Title: Bars, rectangles with bases on x-axis}
\hlcomment{### Aliases: geom_bar}
\hlcomment{### ** Examples}
\hlcomment{## No test: }
\hlcomment{# Generate data}
c <- \hlfunctioncall{ggplot}(mtcars, \hlfunctioncall{aes}(\hlfunctioncall{factor}(cyl)))
c + \hlfunctioncall{geom_bar}()
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_bar1}
\begin{kframe}\begin{alltt}
c + \hlfunctioncall{geom_bar}(width=.5)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_bar2}
\begin{kframe}\begin{alltt}
c + \hlfunctioncall{geom_bar}() + \hlfunctioncall{coord_flip}()
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_bar3}
\begin{kframe}\begin{alltt}
c + \hlfunctioncall{geom_bar}(fill=\hlstring{"white"}, colour=\hlstring{"darkgreen"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_bar4}
\begin{kframe}\begin{alltt}
\hlcomment{# Use qplot}
\hlfunctioncall{qplot}(\hlfunctioncall{factor}(cyl), data=mtcars, geom=\hlstring{"bar"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_bar5}
\begin{kframe}\begin{alltt}
\hlfunctioncall{qplot}(\hlfunctioncall{factor}(cyl), data=mtcars, geom=\hlstring{"bar"}, fill=\hlfunctioncall{factor}(cyl))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_bar6}
\begin{kframe}\begin{alltt}
\hlcomment{# Stacked bar charts}
\hlfunctioncall{qplot}(\hlfunctioncall{factor}(cyl), data=mtcars, geom=\hlstring{"bar"}, fill=\hlfunctioncall{factor}(vs))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_bar7}
\begin{kframe}\begin{alltt}
\hlfunctioncall{qplot}(\hlfunctioncall{factor}(cyl), data=mtcars, geom=\hlstring{"bar"}, fill=\hlfunctioncall{factor}(gear))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_bar8}
\begin{kframe}\begin{alltt}
\hlcomment{# Stacked bar charts are easy in ggplot2, but not effective visually,}
\hlcomment{# particularly when there are many different things being stacked}
\hlfunctioncall{ggplot}(diamonds, \hlfunctioncall{aes}(clarity, fill=cut)) + \hlfunctioncall{geom_bar}()
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_bar9}
\begin{kframe}\begin{alltt}
\hlfunctioncall{ggplot}(diamonds, \hlfunctioncall{aes}(color, fill=cut)) + \hlfunctioncall{geom_bar}() + \hlfunctioncall{coord_flip}()
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_bar10}
\begin{kframe}\begin{alltt}
\hlcomment{# Faceting is a good alternative:}
\hlfunctioncall{ggplot}(diamonds, \hlfunctioncall{aes}(clarity)) + \hlfunctioncall{geom_bar}() +
\hlfunctioncall{facet_wrap}(~ cut)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_bar11}
\begin{kframe}\begin{alltt}
\hlcomment{# If the x axis is ordered, using a line instead of bars is another}
\hlcomment{# possibility:}
\hlfunctioncall{ggplot}(diamonds, \hlfunctioncall{aes}(clarity)) +
\hlfunctioncall{geom_freqpoly}(\hlfunctioncall{aes}(group = cut, colour = cut))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_bar12}
\begin{kframe}\begin{alltt}
\hlcomment{# Dodged bar charts}
\hlfunctioncall{ggplot}(diamonds, \hlfunctioncall{aes}(clarity, fill=cut)) + \hlfunctioncall{geom_bar}(position=\hlstring{"dodge"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_bar13}
\begin{kframe}\begin{alltt}
\hlcomment{# compare with}
\hlfunctioncall{ggplot}(diamonds, \hlfunctioncall{aes}(cut, fill=cut)) + \hlfunctioncall{geom_bar}() +
\hlfunctioncall{facet_grid}(. ~ clarity)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_bar14}
\begin{kframe}\begin{alltt}
\hlcomment{# But again, probably better to use frequency polygons instead:}
\hlfunctioncall{ggplot}(diamonds, \hlfunctioncall{aes}(clarity, colour=cut)) +
\hlfunctioncall{geom_freqpoly}(\hlfunctioncall{aes}(group = cut))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_bar15}
\begin{kframe}\begin{alltt}
\hlcomment{# Often we don't want the height of the bar to represent the}
\hlcomment{# count of observations, but the sum of some other variable.}
\hlcomment{# For example, the following plot shows the number of diamonds}
\hlcomment{# of each colour}
\hlfunctioncall{qplot}(color, data=diamonds, geom=\hlstring{"bar"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_bar16}
\begin{kframe}\begin{alltt}
\hlcomment{# If, however, we want to see the total number of carats in each colour}
\hlcomment{# we need to weight by the carat variable}
\hlfunctioncall{qplot}(color, data=diamonds, geom=\hlstring{"bar"}, weight=carat, ylab=\hlstring{"carat"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_bar17}
\begin{kframe}\begin{alltt}
\hlcomment{# A bar chart used to display means}
meanprice <- \hlfunctioncall{tapply}(diamonds$price, diamonds$cut, mean)
cut <- \hlfunctioncall{factor}(\hlfunctioncall{levels}(diamonds$cut), levels = \hlfunctioncall{levels}(diamonds$cut))
\hlfunctioncall{qplot}(cut, meanprice)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_bar18}
\begin{kframe}\begin{alltt}
\hlfunctioncall{qplot}(cut, meanprice, geom=\hlstring{"bar"}, stat=\hlstring{"identity"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_bar19}
\begin{kframe}\begin{alltt}
\hlfunctioncall{qplot}(cut, meanprice, geom=\hlstring{"bar"}, stat=\hlstring{"identity"}, fill = \hlfunctioncall{I}(\hlstring{"grey50"}))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_bar20}
\begin{kframe}\begin{alltt}
\hlcomment{# Another stacked bar chart example}
k <- \hlfunctioncall{ggplot}(mpg, \hlfunctioncall{aes}(manufacturer, fill=class))
k + \hlfunctioncall{geom_bar}()
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_bar21}
\begin{kframe}\begin{alltt}
\hlcomment{# Use scales to change aesthetics defaults}
k + \hlfunctioncall{geom_bar}() + \hlfunctioncall{scale_fill_brewer}()
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_bar22}
\begin{kframe}\begin{alltt}
k + \hlfunctioncall{geom_bar}() + \hlfunctioncall{scale_fill_grey}()
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_bar23}
\begin{kframe}\begin{alltt}
\hlcomment{# To change plot order of class varible}
\hlcomment{# use factor() to change order of levels}
mpg$class <- \hlfunctioncall{factor}(mpg$class, levels = \hlfunctioncall{c}(\hlstring{"midsize"}, \hlstring{"minivan"},
\hlstring{"suv"}, \hlstring{"compact"}, \hlstring{"2seater"}, \hlstring{"subcompact"}, \hlstring{"pickup"}))
m <- \hlfunctioncall{ggplot}(mpg, \hlfunctioncall{aes}(manufacturer, fill=class))
m + \hlfunctioncall{geom_bar}()
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_bar24}
\begin{kframe}\begin{alltt}
\hlcomment{## End(No test)}
\end{alltt}
\end{kframe}
\end{knitrout}
\section{geom\_bin2d}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlcomment{### Name: geom_bin2d}
\hlcomment{### Title: Add heatmap of 2d bin counts.}
\hlcomment{### Aliases: geom_bin2d}
\hlcomment{### ** Examples}
d <- \hlfunctioncall{ggplot}(diamonds, \hlfunctioncall{aes}(x = x, y = y)) + \hlfunctioncall{xlim}(4,10) + \hlfunctioncall{ylim}(4,10)
d + \hlfunctioncall{geom_bin2d}()
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_bin2d1}
\begin{kframe}\begin{alltt}
d + \hlfunctioncall{geom_bin2d}(binwidth = \hlfunctioncall{c}(0.1, 0.1))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_bin2d2}
\begin{kframe}\begin{alltt}
\hlcomment{# See ?stat_bin2d for more examples}
\end{alltt}
\end{kframe}
\end{knitrout}
\section{geom\_blank}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlcomment{### Name: geom_blank}
\hlcomment{### Title: Blank, draws nothing.}
\hlcomment{### Aliases: geom_blank}
\hlcomment{### ** Examples}
\hlfunctioncall{qplot}(length, rating, data = movies, geom = \hlstring{"blank"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_blank1}
\begin{kframe}\begin{alltt}
\hlcomment{# Nothing to see here!}
\hlcomment{# Take the following scatter plot}
a <- \hlfunctioncall{ggplot}(mtcars, \hlfunctioncall{aes}(x = wt, y = mpg), . ~ cyl) + \hlfunctioncall{geom_point}()
\hlcomment{# Add to that some lines with geom_abline()}
df <- \hlfunctioncall{data.frame}(a = \hlfunctioncall{rnorm}(10, 25), b = \hlfunctioncall{rnorm}(10, 0))
a + \hlfunctioncall{geom_abline}(\hlfunctioncall{aes}(intercept = a, slope = b), data = df)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_blank2}
\begin{kframe}\begin{alltt}
\hlcomment{# Suppose you then wanted to remove the geom_point layer}
\hlcomment{# If you just remove geom_point, you will get an error}
b <- \hlfunctioncall{ggplot}(mtcars, \hlfunctioncall{aes}(x = wt, y = mpg))
\hlcomment{## Not run: b + geom_abline(aes(intercept = a, slope = b), data = df)}
\hlcomment{# Switching to geom_blank() gets the desired plot}
c <- \hlfunctioncall{ggplot}(mtcars, \hlfunctioncall{aes}(x = wt, y = mpg)) + \hlfunctioncall{geom_blank}()
c + \hlfunctioncall{geom_abline}(\hlfunctioncall{aes}(intercept = a, slope = b), data = df)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_blank3}
\begin{kframe}\begin{alltt}
\end{alltt}
\end{kframe}
\end{knitrout}
\section{geom\_boxplot}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlcomment{### Name: geom_boxplot}
\hlcomment{### Title: Box and whiskers plot.}
\hlcomment{### Aliases: geom_boxplot}
\hlcomment{### ** Examples}
\hlcomment{## No test: }
p <- \hlfunctioncall{ggplot}(mtcars, \hlfunctioncall{aes}(\hlfunctioncall{factor}(cyl), mpg))
p + \hlfunctioncall{geom_boxplot}()
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_boxplot1}
\begin{kframe}\begin{alltt}
\hlfunctioncall{qplot}(\hlfunctioncall{factor}(cyl), mpg, data = mtcars, geom = \hlstring{"boxplot"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_boxplot2}
\begin{kframe}\begin{alltt}
p + \hlfunctioncall{geom_boxplot}() + \hlfunctioncall{geom_jitter}()
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_boxplot3}
\begin{kframe}\begin{alltt}
p + \hlfunctioncall{geom_boxplot}() + \hlfunctioncall{coord_flip}()
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_boxplot4}
\begin{kframe}\begin{alltt}
\hlfunctioncall{qplot}(\hlfunctioncall{factor}(cyl), mpg, data = mtcars, geom = \hlstring{"boxplot"}) +
\hlfunctioncall{coord_flip}()
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_boxplot5}
\begin{kframe}\begin{alltt}
p + \hlfunctioncall{geom_boxplot}(notch = TRUE)
\end{alltt}
{\ttfamily\noindent\textcolor{warningcolor}{\#\# Warning: notch went outside hinges. Try setting notch=FALSE.}}
{\ttfamily\noindent\textcolor{warningcolor}{\#\# Warning: notch went outside hinges. Try setting notch=FALSE.}}\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_boxplot6}
\begin{kframe}\begin{alltt}
p + \hlfunctioncall{geom_boxplot}(notch = TRUE, notchwidth = .3)
\end{alltt}
{\ttfamily\noindent\textcolor{warningcolor}{\#\# Warning: notch went outside hinges. Try setting notch=FALSE.}}
{\ttfamily\noindent\textcolor{warningcolor}{\#\# Warning: notch went outside hinges. Try setting notch=FALSE.}}\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_boxplot7}
\begin{kframe}\begin{alltt}
p + \hlfunctioncall{geom_boxplot}(outlier.colour = \hlstring{"green"}, outlier.size = 3)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_boxplot8}
\begin{kframe}\begin{alltt}
\hlcomment{# Add aesthetic mappings}
\hlcomment{# Note that boxplots are automatically dodged when any aesthetic is}
\hlcomment{# a factor}
p + \hlfunctioncall{geom_boxplot}(\hlfunctioncall{aes}(fill = cyl))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_boxplot9}
\begin{kframe}\begin{alltt}
p + \hlfunctioncall{geom_boxplot}(\hlfunctioncall{aes}(fill = \hlfunctioncall{factor}(cyl)))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_boxplot10}
\begin{kframe}\begin{alltt}
p + \hlfunctioncall{geom_boxplot}(\hlfunctioncall{aes}(fill = \hlfunctioncall{factor}(vs)))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_boxplot11}
\begin{kframe}\begin{alltt}
p + \hlfunctioncall{geom_boxplot}(\hlfunctioncall{aes}(fill = \hlfunctioncall{factor}(am)))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_boxplot12}
\begin{kframe}\begin{alltt}
\hlcomment{# Set aesthetics to fixed value}
p + \hlfunctioncall{geom_boxplot}(fill = \hlstring{"grey80"}, colour = \hlstring{"#3366FF"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_boxplot13}
\begin{kframe}\begin{alltt}
\hlfunctioncall{qplot}(\hlfunctioncall{factor}(cyl), mpg, data = mtcars, geom = \hlstring{"boxplot"},
colour = \hlfunctioncall{I}(\hlstring{"#3366FF"}))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_boxplot14}
\begin{kframe}\begin{alltt}
\hlcomment{# Scales vs. coordinate transforms -------}
\hlcomment{# Scale transformations occur before the boxplot statistics are computed.}
\hlcomment{# Coordinate transformations occur afterwards. Observe the effect on the}
\hlcomment{# number of outliers.}
\hlfunctioncall{library}(plyr) \hlcomment{# to access round_any}
m <- \hlfunctioncall{ggplot}(movies, \hlfunctioncall{aes}(y = votes, x = rating,
group = \hlfunctioncall{round_any}(rating, 0.5)))
m + \hlfunctioncall{geom_boxplot}()
\end{alltt}
{\ttfamily\noindent\textcolor{warningcolor}{\#\# Warning: position\_dodge requires constant width: output may be incorrect}}\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_boxplot15}
\begin{kframe}\begin{alltt}
m + \hlfunctioncall{geom_boxplot}() + \hlfunctioncall{scale_y_log10}()
\end{alltt}
{\ttfamily\noindent\textcolor{warningcolor}{\#\# Warning: position\_dodge requires constant width: output may be incorrect}}\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_boxplot16}
\begin{kframe}\begin{alltt}
m + \hlfunctioncall{geom_boxplot}() + \hlfunctioncall{coord_trans}(y = \hlstring{"log10"})
\end{alltt}
{\ttfamily\noindent\textcolor{warningcolor}{\#\# Warning: position\_dodge requires constant width: output may be incorrect}}\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_boxplot17}
\begin{kframe}\begin{alltt}
m + \hlfunctioncall{geom_boxplot}() + \hlfunctioncall{scale_y_log10}() + \hlfunctioncall{coord_trans}(y = \hlstring{"log10"})
\end{alltt}
{\ttfamily\noindent\textcolor{warningcolor}{\#\# Warning: position\_dodge requires constant width: output may be incorrect}}\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_boxplot18}
\begin{kframe}\begin{alltt}
\hlcomment{# Boxplots with continuous x:}
\hlcomment{# Use the group aesthetic to group observations in boxplots}
\hlfunctioncall{qplot}(year, budget, data = movies, geom = \hlstring{"boxplot"})
\end{alltt}
{\ttfamily\noindent\textcolor{warningcolor}{\#\# Warning: Removed 53573 rows containing non-finite values (stat\_boxplot).}}\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_boxplot19}
\begin{kframe}\begin{alltt}
\hlfunctioncall{qplot}(year, budget, data = movies, geom = \hlstring{"boxplot"},
group = \hlfunctioncall{round_any}(year, 10, floor))
\end{alltt}
{\ttfamily\noindent\textcolor{warningcolor}{\#\# Warning: Removed 53573 rows containing non-finite values (stat\_boxplot).}}
{\ttfamily\noindent\textcolor{warningcolor}{\#\# Warning: position\_dodge requires constant width: output may be incorrect}}\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_boxplot20}
\begin{kframe}\begin{alltt}
\hlcomment{# Using precomputed statistics}
\hlcomment{# generate sample data}
abc <- \hlfunctioncall{adply}(\hlfunctioncall{matrix}(\hlfunctioncall{rnorm}(100), ncol = 5), 2, quantile, \hlfunctioncall{c}(0, .25, .5, .75, 1))
b <- \hlfunctioncall{ggplot}(abc, \hlfunctioncall{aes}(x = X1, ymin = `0%`, lower = `25%`, middle = `50%`, upper = `75%`, ymax = `100%`))
b + \hlfunctioncall{geom_boxplot}(stat = \hlstring{"identity"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_boxplot21}
\begin{kframe}\begin{alltt}
b + \hlfunctioncall{geom_boxplot}(stat = \hlstring{"identity"}) + \hlfunctioncall{coord_flip}()
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_boxplot22}
\begin{kframe}\begin{alltt}
b + \hlfunctioncall{geom_boxplot}(\hlfunctioncall{aes}(fill = X1), stat = \hlstring{"identity"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_boxplot23}
\begin{kframe}\begin{alltt}
\hlcomment{## End(No test)}
\end{alltt}
\end{kframe}
\end{knitrout}
\section{geom\_contour}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlcomment{### Name: geom_contour}
\hlcomment{### Title: Display contours of a 3d surface in 2d.}
\hlcomment{### Aliases: geom_contour}
\hlcomment{### ** Examples}
\hlcomment{# See stat_contour for examples}
\end{alltt}
\end{kframe}
\end{knitrout}
\section{geom\_crossbar}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlcomment{### Name: geom_crossbar}
\hlcomment{### Title: Hollow bar with middle indicated by horizontal line.}
\hlcomment{### Aliases: geom_crossbar}
\hlcomment{### ** Examples}
\hlcomment{# See geom_linerange for examples}
\end{alltt}
\end{kframe}
\end{knitrout}
\section{geom\_density}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlcomment{### Name: geom_density}
\hlcomment{### Title: Display a smooth density estimate.}
\hlcomment{### Aliases: geom_density}
\hlcomment{### ** Examples}
\hlcomment{# See stat_density for examples}
\end{alltt}
\end{kframe}
\end{knitrout}
\section{geom\_density2d}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlcomment{### Name: geom_density2d}
\hlcomment{### Title: Contours from a 2d density estimate.}
\hlcomment{### Aliases: geom_density2d}
\hlcomment{### ** Examples}
\hlcomment{# See stat_density2d for examples}
\end{alltt}
\end{kframe}
\end{knitrout}
\section{geom\_dotplot}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlcomment{### Name: geom_dotplot}
\hlcomment{### Title: Dot plot}
\hlcomment{### Aliases: geom_dotplot}
\hlcomment{### ** Examples}
\hlfunctioncall{ggplot}(mtcars, \hlfunctioncall{aes}(x = mpg)) + \hlfunctioncall{geom_dotplot}()
\end{alltt}
{\ttfamily\noindent\itshape\textcolor{messagecolor}{\#\# stat\_bindot: binwidth defaulted to range/30. Use 'binwidth = x' to adjust this.}}\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_dotplot1}
\begin{kframe}\begin{alltt}
\hlfunctioncall{ggplot}(mtcars, \hlfunctioncall{aes}(x = mpg)) + \hlfunctioncall{geom_dotplot}(binwidth = 1.5)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_dotplot2}
\begin{kframe}\begin{alltt}
\hlcomment{# Use fixed-width bins}
\hlfunctioncall{ggplot}(mtcars, \hlfunctioncall{aes}(x = mpg)) +
\hlfunctioncall{geom_dotplot}(method=\hlstring{"histodot"}, binwidth = 1.5)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_dotplot3}
\begin{kframe}\begin{alltt}
\hlcomment{# Some other stacking methods}
\hlfunctioncall{ggplot}(mtcars, \hlfunctioncall{aes}(x = mpg)) +
\hlfunctioncall{geom_dotplot}(binwidth = 1.5, stackdir = \hlstring{"center"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_dotplot4}
\begin{kframe}\begin{alltt}
\hlfunctioncall{ggplot}(mtcars, \hlfunctioncall{aes}(x = mpg)) +
\hlfunctioncall{geom_dotplot}(binwidth = 1.5, stackdir = \hlstring{"centerwhole"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_dotplot5}
\begin{kframe}\begin{alltt}
\hlcomment{# y axis isn't really meaningful, so hide it}
\hlfunctioncall{ggplot}(mtcars, \hlfunctioncall{aes}(x = mpg)) + \hlfunctioncall{geom_dotplot}(binwidth = 1.5) +
\hlfunctioncall{scale_y_continuous}(name = \hlstring{""}, breaks = NA)
\end{alltt}
{\ttfamily\noindent\textcolor{warningcolor}{\#\# Warning: breaks = NA is deprecated. Please use breaks = NULL to remove breaks in the scale.}}\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_dotplot6}
\begin{kframe}\begin{alltt}
\hlcomment{# Overlap dots vertically}
\hlfunctioncall{ggplot}(mtcars, \hlfunctioncall{aes}(x = mpg)) + \hlfunctioncall{geom_dotplot}(binwidth = 1.5, stackratio = .7)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_dotplot7}
\begin{kframe}\begin{alltt}
\hlcomment{# Expand dot diameter}
\hlfunctioncall{ggplot}(mtcars, \hlfunctioncall{aes}(x =mpg)) + \hlfunctioncall{geom_dotplot}(binwidth = 1.5, dotsize = 1.25)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_dotplot8}
\begin{kframe}\begin{alltt}
\hlcomment{# Examples with stacking along y axis instead of x}
\hlfunctioncall{ggplot}(mtcars, \hlfunctioncall{aes}(x = 1, y = mpg)) +
\hlfunctioncall{geom_dotplot}(binaxis = \hlstring{"y"}, stackdir = \hlstring{"center"})
\end{alltt}
{\ttfamily\noindent\itshape\textcolor{messagecolor}{\#\# stat\_bindot: binwidth defaulted to range/30. Use 'binwidth = x' to adjust this.}}\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_dotplot9}
\begin{kframe}\begin{alltt}
\hlfunctioncall{ggplot}(mtcars, \hlfunctioncall{aes}(x = \hlfunctioncall{factor}(cyl), y = mpg)) +
\hlfunctioncall{geom_dotplot}(binaxis = \hlstring{"y"}, stackdir = \hlstring{"center"})
\end{alltt}
{\ttfamily\noindent\itshape\textcolor{messagecolor}{\#\# stat\_bindot: binwidth defaulted to range/30. Use 'binwidth = x' to adjust this.}}\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_dotplot10}
\begin{kframe}\begin{alltt}
\hlfunctioncall{ggplot}(mtcars, \hlfunctioncall{aes}(x = \hlfunctioncall{factor}(cyl), y = mpg)) +
\hlfunctioncall{geom_dotplot}(binaxis = \hlstring{"y"}, stackdir = \hlstring{"centerwhole"})
\end{alltt}
{\ttfamily\noindent\itshape\textcolor{messagecolor}{\#\# stat\_bindot: binwidth defaulted to range/30. Use 'binwidth = x' to adjust this.}}\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_dotplot11}
\begin{kframe}\begin{alltt}
\hlfunctioncall{ggplot}(mtcars, \hlfunctioncall{aes}(x = \hlfunctioncall{factor}(vs), fill = \hlfunctioncall{factor}(cyl), y = mpg)) +
\hlfunctioncall{geom_dotplot}(binaxis = \hlstring{"y"}, stackdir = \hlstring{"center"}, position = \hlstring{"dodge"})
\end{alltt}
{\ttfamily\noindent\itshape\textcolor{messagecolor}{\#\# stat\_bindot: binwidth defaulted to range/30. Use 'binwidth = x' to adjust this.}}\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_dotplot12}
\begin{kframe}\begin{alltt}
\hlcomment{# binpositions="all" ensures that the bins are aligned between groups}
\hlfunctioncall{ggplot}(mtcars, \hlfunctioncall{aes}(x = \hlfunctioncall{factor}(am), y = mpg)) +
\hlfunctioncall{geom_dotplot}(binaxis = \hlstring{"y"}, stackdir = \hlstring{"center"}, binpositions=\hlstring{"all"})
\end{alltt}
{\ttfamily\noindent\itshape\textcolor{messagecolor}{\#\# stat\_bindot: binwidth defaulted to range/30. Use 'binwidth = x' to adjust this.}}\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_dotplot13}
\begin{kframe}\begin{alltt}
\hlcomment{# Stacking multiple groups, with different fill}
\hlfunctioncall{ggplot}(mtcars, \hlfunctioncall{aes}(x = mpg, fill = \hlfunctioncall{factor}(cyl))) +
\hlfunctioncall{geom_dotplot}(stackgroups = TRUE, binwidth = 1, binpositions = \hlstring{"all"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_dotplot14}
\begin{kframe}\begin{alltt}
\hlfunctioncall{ggplot}(mtcars, \hlfunctioncall{aes}(x = mpg, fill = \hlfunctioncall{factor}(cyl))) +
\hlfunctioncall{geom_dotplot}(stackgroups = TRUE, binwidth = 1, method = \hlstring{"histodot"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_dotplot15}
\begin{kframe}\begin{alltt}
\hlfunctioncall{ggplot}(mtcars, \hlfunctioncall{aes}(x = 1, y = mpg, fill = \hlfunctioncall{factor}(cyl))) +
\hlfunctioncall{geom_dotplot}(binaxis = \hlstring{"y"}, stackgroups = TRUE, binwidth = 1, method = \hlstring{"histodot"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_dotplot16}
\begin{kframe}\begin{alltt}
\end{alltt}
\end{kframe}
\end{knitrout}
\section{geom\_errorbar}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlcomment{### Name: geom_errorbar}
\hlcomment{### Title: Error bars.}
\hlcomment{### Aliases: geom_errorbar}
\hlcomment{### ** Examples}
\hlcomment{# Create a simple example dataset}
df <- \hlfunctioncall{data.frame}(
trt = \hlfunctioncall{factor}(\hlfunctioncall{c}(1, 1, 2, 2)),
resp = \hlfunctioncall{c}(1, 5, 3, 4),
group = \hlfunctioncall{factor}(\hlfunctioncall{c}(1, 2, 1, 2)),
se = \hlfunctioncall{c}(0.1, 0.3, 0.3, 0.2)
)
df2 <- df[\hlfunctioncall{c}(1,3),]
\hlcomment{# Define the top and bottom of the errorbars}
limits <- \hlfunctioncall{aes}(ymax = resp + se, ymin=resp - se)
p <- \hlfunctioncall{ggplot}(df, \hlfunctioncall{aes}(fill=group, y=resp, x=trt))
p + \hlfunctioncall{geom_bar}(position=\hlstring{"dodge"}, stat=\hlstring{"identity"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_errorbar1}
\begin{kframe}\begin{alltt}
\hlcomment{# Because the bars and errorbars have different widths}
\hlcomment{# we need to specify how wide the objects we are dodging are}
dodge <- \hlfunctioncall{position_dodge}(width=0.9)
p + \hlfunctioncall{geom_bar}(position=dodge) + \hlfunctioncall{geom_errorbar}(limits, position=dodge, width=0.25)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_errorbar2}
\begin{kframe}\begin{alltt}
p <- \hlfunctioncall{ggplot}(df2, \hlfunctioncall{aes}(fill=group, y=resp, x=trt))
p + \hlfunctioncall{geom_bar}(position=dodge)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_errorbar3}
\begin{kframe}\begin{alltt}
p + \hlfunctioncall{geom_bar}(position=dodge) + \hlfunctioncall{geom_errorbar}(limits, position=dodge, width=0.25)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_errorbar4}
\begin{kframe}\begin{alltt}
p <- \hlfunctioncall{ggplot}(df, \hlfunctioncall{aes}(colour=group, y=resp, x=trt))
p + \hlfunctioncall{geom_point}() + \hlfunctioncall{geom_errorbar}(limits, width=0.2)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_errorbar5}
\begin{kframe}\begin{alltt}
p + \hlfunctioncall{geom_pointrange}(limits)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_errorbar6}
\begin{kframe}\begin{alltt}
p + \hlfunctioncall{geom_crossbar}(limits, width=0.2)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_errorbar7}
\begin{kframe}\begin{alltt}
\hlcomment{# If we want to draw lines, we need to manually set the}
\hlcomment{# groups which define the lines - here the groups in the}
\hlcomment{# original dataframe}
p + \hlfunctioncall{geom_line}(\hlfunctioncall{aes}(group=group)) + \hlfunctioncall{geom_errorbar}(limits, width=0.2)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_errorbar8}
\begin{kframe}\begin{alltt}
\end{alltt}
\end{kframe}
\end{knitrout}
\section{geom\_errorbarh}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlcomment{### Name: geom_errorbarh}
\hlcomment{### Title: Horizontal error bars}
\hlcomment{### Aliases: geom_errorbarh}
\hlcomment{### ** Examples}
df <- \hlfunctioncall{data.frame}(
trt = \hlfunctioncall{factor}(\hlfunctioncall{c}(1, 1, 2, 2)),
resp = \hlfunctioncall{c}(1, 5, 3, 4),
group = \hlfunctioncall{factor}(\hlfunctioncall{c}(1, 2, 1, 2)),
se = \hlfunctioncall{c}(0.1, 0.3, 0.3, 0.2)
)
\hlcomment{# Define the top and bottom of the errorbars}
p <- \hlfunctioncall{ggplot}(df, \hlfunctioncall{aes}(resp, trt, colour = group))
p + \hlfunctioncall{geom_point}() +
\hlfunctioncall{geom_errorbarh}(\hlfunctioncall{aes}(xmax = resp + se, xmin = resp - se))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_errorbarh1}
\begin{kframe}\begin{alltt}
p + \hlfunctioncall{geom_point}() +
\hlfunctioncall{geom_errorbarh}(\hlfunctioncall{aes}(xmax = resp + se, xmin = resp - se, height = .2))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_errorbarh2}
\begin{kframe}\begin{alltt}
\end{alltt}
\end{kframe}
\end{knitrout}
\section{geom\_freqpoly}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlcomment{### Name: geom_freqpoly}
\hlcomment{### Title: Frequency polygon.}
\hlcomment{### Aliases: geom_freqpoly}
\hlcomment{### ** Examples}
\hlfunctioncall{qplot}(carat, data = diamonds, geom = \hlstring{"freqpoly"})
\end{alltt}
{\ttfamily\noindent\itshape\textcolor{messagecolor}{\#\# stat\_bin: binwidth defaulted to range/30. Use 'binwidth = x' to adjust this.}}\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_freqpoly1}
\begin{kframe}\begin{alltt}
\hlfunctioncall{qplot}(carat, data = diamonds, geom = \hlstring{"freqpoly"}, binwidth = 0.1)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_freqpoly2}
\begin{kframe}\begin{alltt}
\hlfunctioncall{qplot}(carat, data = diamonds, geom = \hlstring{"freqpoly"}, binwidth = 0.01)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_freqpoly3}
\begin{kframe}\begin{alltt}
\hlfunctioncall{qplot}(price, data = diamonds, geom = \hlstring{"freqpoly"}, binwidth = 1000)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_freqpoly4}
\begin{kframe}\begin{alltt}
\hlfunctioncall{qplot}(price, data = diamonds, geom = \hlstring{"freqpoly"}, binwidth = 1000,
colour = color)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_freqpoly5}
\begin{kframe}\begin{alltt}
\hlfunctioncall{qplot}(price, ..density.., data = diamonds, geom = \hlstring{"freqpoly"},
binwidth = 1000, colour = color)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_freqpoly6}
\begin{kframe}\begin{alltt}
\end{alltt}
\end{kframe}
\end{knitrout}
\section{geom\_hex}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlcomment{### Name: geom_hex}
\hlcomment{### Title: Hexagon bining.}
\hlcomment{### Aliases: geom_hex}
\hlcomment{### ** Examples}
\hlcomment{# See ?stat_binhex for examples}
\end{alltt}
\end{kframe}
\end{knitrout}
\section{geom\_histogram}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlcomment{### Name: geom_histogram}
\hlcomment{### Title: Histogram}
\hlcomment{### Aliases: geom_histogram}
\hlcomment{### ** Examples}
\hlcomment{## No test: }
\hlfunctioncall{set.seed}(5689)
movies <- movies[\hlfunctioncall{sample}(\hlfunctioncall{nrow}(movies), 1000), ]
\hlcomment{# Simple examples}
\hlfunctioncall{qplot}(rating, data=movies, geom=\hlstring{"histogram"})
\end{alltt}
{\ttfamily\noindent\itshape\textcolor{messagecolor}{\#\# stat\_bin: binwidth defaulted to range/30. Use 'binwidth = x' to adjust this.}}
{\ttfamily\noindent\textcolor{warningcolor}{\#\# Warning: position\_stack requires constant width: output may be incorrect}}\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_histogram1}
\begin{kframe}\begin{alltt}
\hlfunctioncall{qplot}(rating, data=movies, weight=votes, geom=\hlstring{"histogram"})
\end{alltt}
{\ttfamily\noindent\itshape\textcolor{messagecolor}{\#\# stat\_bin: binwidth defaulted to range/30. Use 'binwidth = x' to adjust this.}}
{\ttfamily\noindent\textcolor{warningcolor}{\#\# Warning: position\_stack requires constant width: output may be incorrect}}\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_histogram2}
\begin{kframe}\begin{alltt}
\hlfunctioncall{qplot}(rating, data=movies, weight=votes, geom=\hlstring{"histogram"}, binwidth=1)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_histogram3}
\begin{kframe}\begin{alltt}
\hlfunctioncall{qplot}(rating, data=movies, weight=votes, geom=\hlstring{"histogram"}, binwidth=0.1)
\end{alltt}
{\ttfamily\noindent\textcolor{warningcolor}{\#\# Warning: position\_stack requires constant width: output may be incorrect}}\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_histogram4}
\begin{kframe}\begin{alltt}
\hlcomment{# More complex}
m <- \hlfunctioncall{ggplot}(movies, \hlfunctioncall{aes}(x=rating))
m + \hlfunctioncall{geom_histogram}()
\end{alltt}
{\ttfamily\noindent\itshape\textcolor{messagecolor}{\#\# stat\_bin: binwidth defaulted to range/30. Use 'binwidth = x' to adjust this.}}
{\ttfamily\noindent\textcolor{warningcolor}{\#\# Warning: position\_stack requires constant width: output may be incorrect}}\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_histogram5}
\begin{kframe}\begin{alltt}
m + \hlfunctioncall{geom_histogram}(\hlfunctioncall{aes}(y = ..density..)) + \hlfunctioncall{geom_density}()
\end{alltt}
{\ttfamily\noindent\itshape\textcolor{messagecolor}{\#\# stat\_bin: binwidth defaulted to range/30. Use 'binwidth = x' to adjust this.}}
{\ttfamily\noindent\textcolor{warningcolor}{\#\# Warning: position\_stack requires constant width: output may be incorrect}}\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_histogram6}
\begin{kframe}\begin{alltt}
m + \hlfunctioncall{geom_histogram}(binwidth = 1)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_histogram7}
\begin{kframe}\begin{alltt}
m + \hlfunctioncall{geom_histogram}(binwidth = 0.5)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_histogram8}
\begin{kframe}\begin{alltt}
m + \hlfunctioncall{geom_histogram}(binwidth = 0.1)
\end{alltt}
{\ttfamily\noindent\textcolor{warningcolor}{\#\# Warning: position\_stack requires constant width: output may be incorrect}}\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_histogram9}
\begin{kframe}\begin{alltt}
\hlcomment{# Add aesthetic mappings}
m + \hlfunctioncall{geom_histogram}(\hlfunctioncall{aes}(weight = votes))
\end{alltt}
{\ttfamily\noindent\itshape\textcolor{messagecolor}{\#\# stat\_bin: binwidth defaulted to range/30. Use 'binwidth = x' to adjust this.}}
{\ttfamily\noindent\textcolor{warningcolor}{\#\# Warning: position\_stack requires constant width: output may be incorrect}}\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_histogram10}
\begin{kframe}\begin{alltt}
m + \hlfunctioncall{geom_histogram}(\hlfunctioncall{aes}(y = ..count..))
\end{alltt}
{\ttfamily\noindent\itshape\textcolor{messagecolor}{\#\# stat\_bin: binwidth defaulted to range/30. Use 'binwidth = x' to adjust this.}}
{\ttfamily\noindent\textcolor{warningcolor}{\#\# Warning: position\_stack requires constant width: output may be incorrect}}\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_histogram11}
\begin{kframe}\begin{alltt}
m + \hlfunctioncall{geom_histogram}(\hlfunctioncall{aes}(fill = ..count..))
\end{alltt}
{\ttfamily\noindent\itshape\textcolor{messagecolor}{\#\# stat\_bin: binwidth defaulted to range/30. Use 'binwidth = x' to adjust this.}}
{\ttfamily\noindent\textcolor{warningcolor}{\#\# Warning: position\_stack requires constant width: output may be incorrect}}\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_histogram12}
\begin{kframe}\begin{alltt}
\hlcomment{# Change scales}
m + \hlfunctioncall{geom_histogram}(\hlfunctioncall{aes}(fill = ..count..)) +
\hlfunctioncall{scale_fill_gradient}(\hlstring{"Count"}, low = \hlstring{"green"}, high = \hlstring{"red"})
\end{alltt}
{\ttfamily\noindent\itshape\textcolor{messagecolor}{\#\# stat\_bin: binwidth defaulted to range/30. Use 'binwidth = x' to adjust this.}}
{\ttfamily\noindent\textcolor{warningcolor}{\#\# Warning: position\_stack requires constant width: output may be incorrect}}\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_histogram13}
\begin{kframe}\begin{alltt}
\hlcomment{# Often we don't want the height of the bar to represent the}
\hlcomment{# count of observations, but the sum of some other variable.}
\hlcomment{# For example, the following plot shows the number of movies}
\hlcomment{# in each rating.}
\hlfunctioncall{qplot}(rating, data=movies, geom=\hlstring{"bar"}, binwidth = 0.1)
\end{alltt}
{\ttfamily\noindent\textcolor{warningcolor}{\#\# Warning: position\_stack requires constant width: output may be incorrect}}\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_histogram14}
\begin{kframe}\begin{alltt}
\hlcomment{# If, however, we want to see the number of votes cast in each}
\hlcomment{# category, we need to weight by the votes variable}
\hlfunctioncall{qplot}(rating, data=movies, geom=\hlstring{"bar"}, binwidth = 0.1,
weight=votes, ylab = \hlstring{"votes"})
\end{alltt}
{\ttfamily\noindent\textcolor{warningcolor}{\#\# Warning: position\_stack requires constant width: output may be incorrect}}\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_histogram15}
\begin{kframe}\begin{alltt}
m <- \hlfunctioncall{ggplot}(movies, \hlfunctioncall{aes}(x = votes))
\hlcomment{# For transformed scales, binwidth applies to the transformed data.}
\hlcomment{# The bins have constant width on the transformed scale.}
m + \hlfunctioncall{geom_histogram}() + \hlfunctioncall{scale_x_log10}()
\end{alltt}
{\ttfamily\noindent\itshape\textcolor{messagecolor}{\#\# stat\_bin: binwidth defaulted to range/30. Use 'binwidth = x' to adjust this.}}\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_histogram16}
\begin{kframe}\begin{alltt}
m + \hlfunctioncall{geom_histogram}(binwidth = 1) + \hlfunctioncall{scale_x_log10}()
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_histogram17}
\begin{kframe}\begin{alltt}
m + \hlfunctioncall{geom_histogram}() + \hlfunctioncall{scale_x_sqrt}()
\end{alltt}
{\ttfamily\noindent\itshape\textcolor{messagecolor}{\#\# stat\_bin: binwidth defaulted to range/30. Use 'binwidth = x' to adjust this.}}\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_histogram18}
\begin{kframe}\begin{alltt}
m + \hlfunctioncall{geom_histogram}(binwidth = 10) + \hlfunctioncall{scale_x_sqrt}()
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_histogram19}
\begin{kframe}\begin{alltt}
\hlcomment{# For transformed coordinate systems, the binwidth applies to the}
\hlcomment{# raw data. The bins have constant width on the original scale.}
\hlcomment{# Using log scales does not work here, because the first}
\hlcomment{# bar is anchored at zero, and so when transformed becomes negative}
\hlcomment{# infinity. This is not a problem when transforming the scales, because}
\hlcomment{# no observations have 0 ratings.}
m + \hlfunctioncall{geom_histogram}(origin = 0) + \hlfunctioncall{coord_trans}(x = \hlstring{"log10"})
\end{alltt}
{\ttfamily\noindent\itshape\textcolor{messagecolor}{\#\# stat\_bin: binwidth defaulted to range/30. Use 'binwidth = x' to adjust this.}}\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_histogram20}
\begin{kframe}\begin{alltt}
\hlcomment{# Use origin = 0, to make sure we don't take sqrt of negative values}
m + \hlfunctioncall{geom_histogram}(origin = 0) + \hlfunctioncall{coord_trans}(x = \hlstring{"sqrt"})
\end{alltt}
{\ttfamily\noindent\itshape\textcolor{messagecolor}{\#\# stat\_bin: binwidth defaulted to range/30. Use 'binwidth = x' to adjust this.}}\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_histogram21}
\begin{kframe}\begin{alltt}
m + \hlfunctioncall{geom_histogram}(origin = 0, binwidth = 1000) + \hlfunctioncall{coord_trans}(x = \hlstring{"sqrt"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_histogram22}
\begin{kframe}\begin{alltt}
\hlcomment{# You can also transform the y axis. Remember that the base of the bars}
\hlcomment{# has value 0, so log transformations are not appropriate}
m <- \hlfunctioncall{ggplot}(movies, \hlfunctioncall{aes}(x = rating))
m + \hlfunctioncall{geom_histogram}(binwidth = 0.5) + \hlfunctioncall{scale_y_sqrt}()
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_histogram23}
\begin{kframe}\begin{alltt}
m + \hlfunctioncall{geom_histogram}(binwidth = 0.5) + \hlfunctioncall{scale_y_reverse}()
\end{alltt}
{\ttfamily\noindent\textcolor{warningcolor}{\#\# Warning: Stacking not well defined when ymin != 0}}\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_histogram24}
\begin{kframe}\begin{alltt}
\hlcomment{# Set aesthetics to fixed value}
m + \hlfunctioncall{geom_histogram}(colour = \hlstring{"darkgreen"}, fill = \hlstring{"white"}, binwidth = 0.5)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_histogram25}
\begin{kframe}\begin{alltt}
\hlcomment{# Use facets}
m <- m + \hlfunctioncall{geom_histogram}(binwidth = 0.5)
m + \hlfunctioncall{facet_grid}(Action ~ Comedy)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_histogram26}
\begin{kframe}\begin{alltt}
\hlcomment{# Often more useful to use density on the y axis when facetting}
m <- m + \hlfunctioncall{aes}(y = ..density..)
m + \hlfunctioncall{facet_grid}(Action ~ Comedy)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_histogram27}
\begin{kframe}\begin{alltt}
m + \hlfunctioncall{facet_wrap}(~ mpaa)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_histogram28}
\begin{kframe}\begin{alltt}
\hlcomment{# Multiple histograms on the same graph}
\hlcomment{# see ?position, ?position_fill, etc for more details.}
\hlfunctioncall{set.seed}(6298)
diamonds_small <- diamonds[\hlfunctioncall{sample}(\hlfunctioncall{nrow}(diamonds), 1000), ]
\hlfunctioncall{ggplot}(diamonds_small, \hlfunctioncall{aes}(x=price)) + \hlfunctioncall{geom_bar}()
\end{alltt}
{\ttfamily\noindent\itshape\textcolor{messagecolor}{\#\# stat\_bin: binwidth defaulted to range/30. Use 'binwidth = x' to adjust this.}}\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_histogram29}
\begin{kframe}\begin{alltt}
hist_cut <- \hlfunctioncall{ggplot}(diamonds_small, \hlfunctioncall{aes}(x=price, fill=cut))
hist_cut + \hlfunctioncall{geom_bar}() \hlcomment{# defaults to stacking}
\end{alltt}
{\ttfamily\noindent\itshape\textcolor{messagecolor}{\#\# stat\_bin: binwidth defaulted to range/30. Use 'binwidth = x' to adjust this.}}\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_histogram30}
\begin{kframe}\begin{alltt}
hist_cut + \hlfunctioncall{geom_bar}(position=\hlstring{"fill"})
\end{alltt}
{\ttfamily\noindent\itshape\textcolor{messagecolor}{\#\# stat\_bin: binwidth defaulted to range/30. Use 'binwidth = x' to adjust this.}}\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_histogram31}
\begin{kframe}\begin{alltt}
hist_cut + \hlfunctioncall{geom_bar}(position=\hlstring{"dodge"})
\end{alltt}
{\ttfamily\noindent\itshape\textcolor{messagecolor}{\#\# stat\_bin: binwidth defaulted to range/30. Use 'binwidth = x' to adjust this.}}\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_histogram32}
\begin{kframe}\begin{alltt}
\hlcomment{# This is easy in ggplot2, but not visually effective. It's better}
\hlcomment{# to use a frequency polygon or density plot. Like this:}
\hlfunctioncall{ggplot}(diamonds_small, \hlfunctioncall{aes}(price, ..density.., colour = cut)) +
\hlfunctioncall{geom_freqpoly}(binwidth = 1000)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_histogram33}
\begin{kframe}\begin{alltt}
\hlcomment{# Or this:}
\hlfunctioncall{ggplot}(diamonds_small, \hlfunctioncall{aes}(price, colour = cut)) +
\hlfunctioncall{geom_density}()
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_histogram34}
\begin{kframe}\begin{alltt}
\hlcomment{# Or if you want to be fancy, maybe even this:}
\hlfunctioncall{ggplot}(diamonds_small, \hlfunctioncall{aes}(price, fill = cut)) +
\hlfunctioncall{geom_density}(alpha = 0.2)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_histogram35}
\begin{kframe}\begin{alltt}
\hlcomment{# Which looks better when the distributions are more distinct}
\hlfunctioncall{ggplot}(diamonds_small, \hlfunctioncall{aes}(depth, fill = cut)) +
\hlfunctioncall{geom_density}(alpha = 0.2) + \hlfunctioncall{xlim}(55, 70)
\end{alltt}
{\ttfamily\noindent\textcolor{warningcolor}{\#\# Warning: Removed 2 rows containing non-finite values (stat\_density).}}\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_histogram36}
\begin{kframe}\begin{alltt}
\hlcomment{## End(No test)}
\end{alltt}
\end{kframe}
\end{knitrout}
\section{geom\_hline}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlcomment{### Name: geom_hline}
\hlcomment{### Title: Horizontal line.}
\hlcomment{### Aliases: geom_hline}
\hlcomment{### ** Examples}
p <- \hlfunctioncall{ggplot}(mtcars, \hlfunctioncall{aes}(x = wt, y=mpg)) + \hlfunctioncall{geom_point}()
p + \hlfunctioncall{geom_hline}(\hlfunctioncall{aes}(yintercept=mpg))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_hline1}
\begin{kframe}\begin{alltt}
p + \hlfunctioncall{geom_hline}(yintercept=20)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_hline2}
\begin{kframe}\begin{alltt}
p + \hlfunctioncall{geom_hline}(yintercept=\hlfunctioncall{seq}(10, 30, by=5))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_hline3}
\begin{kframe}\begin{alltt}
\hlcomment{# With coordinate transforms}
p + \hlfunctioncall{geom_hline}(\hlfunctioncall{aes}(yintercept=mpg)) + \hlfunctioncall{coord_equal}()
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_hline4}
\begin{kframe}\begin{alltt}
p + \hlfunctioncall{geom_hline}(\hlfunctioncall{aes}(yintercept=mpg)) + \hlfunctioncall{coord_flip}()
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_hline5}
\begin{kframe}\begin{alltt}
p + \hlfunctioncall{geom_hline}(\hlfunctioncall{aes}(yintercept=mpg)) + \hlfunctioncall{coord_polar}()
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_hline6}
\begin{kframe}\begin{alltt}
\hlcomment{# To display different lines in different facets, you need to}
\hlcomment{# create a data frame.}
p <- \hlfunctioncall{qplot}(mpg, wt, data=mtcars, facets = vs ~ am)
hline.data <- \hlfunctioncall{data.frame}(z = 1:4, vs = \hlfunctioncall{c}(0,0,1,1), am = \hlfunctioncall{c}(0,1,0,1))
p + \hlfunctioncall{geom_hline}(\hlfunctioncall{aes}(yintercept = z), hline.data)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_hline7}
\begin{kframe}\begin{alltt}
\end{alltt}
\end{kframe}
\end{knitrout}
\section{geom\_jitter}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlcomment{### Name: geom_jitter}
\hlcomment{### Title: Points, jittered to reduce overplotting.}
\hlcomment{### Aliases: geom_jitter}
\hlcomment{### ** Examples}
p <- \hlfunctioncall{ggplot}(mpg, \hlfunctioncall{aes}(displ, hwy))
p + \hlfunctioncall{geom_point}()
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_jitter1}
\begin{kframe}\begin{alltt}
p + \hlfunctioncall{geom_point}(position = \hlstring{"jitter"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_jitter2}
\begin{kframe}\begin{alltt}
\hlcomment{# Add aesthetic mappings}
p + \hlfunctioncall{geom_jitter}(\hlfunctioncall{aes}(colour = cyl))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_jitter3}
\begin{kframe}\begin{alltt}
\hlcomment{# Vary parameters}
p + \hlfunctioncall{geom_jitter}(position = \hlfunctioncall{position_jitter}(width = .5))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_jitter4}
\begin{kframe}\begin{alltt}
p + \hlfunctioncall{geom_jitter}(position = \hlfunctioncall{position_jitter}(height = .5))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_jitter5}
\begin{kframe}\begin{alltt}
\hlcomment{# Use qplot instead}
\hlfunctioncall{qplot}(displ, hwy, data = mpg, geom = \hlstring{"jitter"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_jitter6}
\begin{kframe}\begin{alltt}
\hlfunctioncall{qplot}(class, hwy, data = mpg, geom = \hlstring{"jitter"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_jitter7}
\begin{kframe}\begin{alltt}
\hlfunctioncall{qplot}(class, hwy, data = mpg, geom = \hlfunctioncall{c}(\hlstring{"boxplot"}, \hlstring{"jitter"}))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_jitter8}
\begin{kframe}\begin{alltt}
\hlfunctioncall{qplot}(class, hwy, data = mpg, geom = \hlfunctioncall{c}(\hlstring{"jitter"}, \hlstring{"boxplot"}))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_jitter9}
\begin{kframe}\begin{alltt}
\end{alltt}
\end{kframe}
\end{knitrout}
\section{geom\_line}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlcomment{### Name: geom_line}
\hlcomment{### Title: Connect observations, ordered by x value.}
\hlcomment{### Aliases: geom_line}
\hlcomment{### ** Examples}
\hlcomment{# Summarise number of movie ratings by year of movie}
mry <- \hlfunctioncall{do.call}(rbind, \hlfunctioncall{by}(movies, \hlfunctioncall{round}(movies$rating), \hlfunctioncall{function}(df) \{
nums <- \hlfunctioncall{tapply}(df$length, df$year, length)
\hlfunctioncall{data.frame}(rating=\hlfunctioncall{round}(df$rating[1]), year = \hlfunctioncall{as.numeric}(\hlfunctioncall{names}(nums)), number=\hlfunctioncall{as.vector}(nums))
\}))
p <- \hlfunctioncall{ggplot}(mry, \hlfunctioncall{aes}(x=year, y=number, group=rating))
p + \hlfunctioncall{geom_line}()
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_line1}
\begin{kframe}\begin{alltt}
\hlcomment{# Add aesthetic mappings}
p + \hlfunctioncall{geom_line}(\hlfunctioncall{aes}(size = rating))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_line2}
\begin{kframe}\begin{alltt}
p + \hlfunctioncall{geom_line}(\hlfunctioncall{aes}(colour = rating))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_line3}
\begin{kframe}\begin{alltt}
\hlcomment{# Change scale}
p + \hlfunctioncall{geom_line}(\hlfunctioncall{aes}(colour = rating)) + \hlfunctioncall{scale_colour_gradient}(low=\hlstring{"red"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_line4}
\begin{kframe}\begin{alltt}
p + \hlfunctioncall{geom_line}(\hlfunctioncall{aes}(size = rating)) + \hlfunctioncall{scale_size}(range = \hlfunctioncall{c}(0.1, 3))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_line5}
\begin{kframe}\begin{alltt}
\hlcomment{# Set aesthetics to fixed value}
p + \hlfunctioncall{geom_line}(colour = \hlstring{"red"}, size = 1)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_line6}
\begin{kframe}\begin{alltt}
\hlcomment{# Use qplot instead}
\hlfunctioncall{qplot}(year, number, data=mry, group=rating, geom=\hlstring{"line"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_line7}
\begin{kframe}\begin{alltt}
\hlcomment{# Using a time series}
\hlfunctioncall{qplot}(date, pop, data=economics, geom=\hlstring{"line"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_line8}
\begin{kframe}\begin{alltt}
\hlfunctioncall{qplot}(date, pop, data=economics, geom=\hlstring{"line"}, log=\hlstring{"y"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_line9}
\begin{kframe}\begin{alltt}
\hlfunctioncall{qplot}(date, pop, data=\hlfunctioncall{subset}(economics, date > \hlfunctioncall{as.Date}(\hlstring{"2006-1-1"})), geom=\hlstring{"line"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_line10}
\begin{kframe}\begin{alltt}
\hlfunctioncall{qplot}(date, pop, data=economics, size=unemploy/pop, geom=\hlstring{"line"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_line11}
\begin{kframe}\begin{alltt}
\hlcomment{# Use the arrow parameter to add an arrow to the line}
\hlcomment{# See ?grid::arrow for more details}
c <- \hlfunctioncall{ggplot}(economics, \hlfunctioncall{aes}(x = date, y = pop))
\hlcomment{# Arrow defaults to "last"}
\hlfunctioncall{library}(grid)
c + \hlfunctioncall{geom_line}(arrow = \hlfunctioncall{arrow}())
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_line12}
\begin{kframe}\begin{alltt}
c + \hlfunctioncall{geom_line}(arrow = \hlfunctioncall{arrow}(angle = 15, ends = \hlstring{"both"}, type = \hlstring{"closed"}))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_line13}
\begin{kframe}\begin{alltt}
\hlcomment{# See scale_date for examples of plotting multiple times series on}
\hlcomment{# a single graph}
\hlcomment{# A simple pcp example}
y2005 <- \hlfunctioncall{runif}(300, 20, 120)
y2010 <- y2005 * \hlfunctioncall{runif}(300, -1.05, 1.5)
group <- \hlfunctioncall{rep}(LETTERS[1:3], each = 100)
df <- \hlfunctioncall{data.frame}(id = \hlfunctioncall{seq_along}(group), group, y2005, y2010)
\hlfunctioncall{library}(reshape2) \hlcomment{# for melt}
dfm <- \hlfunctioncall{melt}(df, id.var = \hlfunctioncall{c}(\hlstring{"id"}, \hlstring{"group"}))
\hlfunctioncall{ggplot}(dfm, \hlfunctioncall{aes}(variable, value, group = id, colour = group)) +
\hlfunctioncall{geom_path}(alpha = 0.5)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_line14}
\begin{kframe}\begin{alltt}
\end{alltt}
\end{kframe}
\end{knitrout}
\section{geom\_linerange}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlcomment{### Name: geom_linerange}
\hlcomment{### Title: An interval represented by a vertical line.}
\hlcomment{### Aliases: geom_linerange}
\hlcomment{### ** Examples}
\hlcomment{# Generate data: means and standard errors of means for prices}
\hlcomment{# for each type of cut}
dmod <- \hlfunctioncall{lm}(price ~ cut, data=diamonds)
cuts <- \hlfunctioncall{data.frame}(cut=\hlfunctioncall{unique}(diamonds$cut), \hlfunctioncall{predict}(dmod, \hlfunctioncall{data.frame}(cut = \hlfunctioncall{unique}(diamonds$cut)), se=TRUE)[\hlfunctioncall{c}(\hlstring{"fit"},\hlstring{"se.fit"})])
\hlfunctioncall{qplot}(cut, fit, data=cuts)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_linerange1}
\begin{kframe}\begin{alltt}
\hlcomment{# With a bar chart, we are comparing lengths, so the y-axis is}
\hlcomment{# automatically extended to include 0}
\hlfunctioncall{qplot}(cut, fit, data=cuts, geom=\hlstring{"bar"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_linerange2}
\begin{kframe}\begin{alltt}
\hlcomment{# Display estimates and standard errors in various ways}
se <- \hlfunctioncall{ggplot}(cuts, \hlfunctioncall{aes}(cut, fit,
ymin = fit - se.fit, ymax=fit + se.fit, colour = cut))
se + \hlfunctioncall{geom_linerange}()
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_linerange3}
\begin{kframe}\begin{alltt}
se + \hlfunctioncall{geom_pointrange}()
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_linerange4}
\begin{kframe}\begin{alltt}
se + \hlfunctioncall{geom_errorbar}(width = 0.5)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_linerange5}
\begin{kframe}\begin{alltt}
se + \hlfunctioncall{geom_crossbar}(width = 0.5)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_linerange6}
\begin{kframe}\begin{alltt}
\hlcomment{# Use coord_flip to flip the x and y axes}
se + \hlfunctioncall{geom_linerange}() + \hlfunctioncall{coord_flip}()
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_linerange7}
\begin{kframe}\begin{alltt}
\end{alltt}
\end{kframe}
\end{knitrout}
\section{geom\_map}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlcomment{### Name: geom_map}
\hlcomment{### Title: Polygons from a reference map.}
\hlcomment{### Aliases: geom_map}
\hlcomment{### ** Examples}
\hlcomment{# When using geom_polygon, you will typically need two data frames:}
\hlcomment{# one contains the coordinates of each polygon (positions), and the}
\hlcomment{# other the values associated with each polygon (values). An id}
\hlcomment{# variable links the two together}
ids <- \hlfunctioncall{factor}(\hlfunctioncall{c}(\hlstring{"1.1"}, \hlstring{"2.1"}, \hlstring{"1.2"}, \hlstring{"2.2"}, \hlstring{"1.3"}, \hlstring{"2.3"}))
values <- \hlfunctioncall{data.frame}(
id = ids,
value = \hlfunctioncall{c}(3, 3.1, 3.1, 3.2, 3.15, 3.5)
)
positions <- \hlfunctioncall{data.frame}(
id = \hlfunctioncall{rep}(ids, each = 4),
x = \hlfunctioncall{c}(2, 1, 1.1, 2.2, 1, 0, 0.3, 1.1, 2.2, 1.1, 1.2, 2.5, 1.1, 0.3,
0.5, 1.2, 2.5, 1.2, 1.3, 2.7, 1.2, 0.5, 0.6, 1.3),
y = \hlfunctioncall{c}(-0.5, 0, 1, 0.5, 0, 0.5, 1.5, 1, 0.5, 1, 2.1, 1.7, 1, 1.5,
2.2, 2.1, 1.7, 2.1, 3.2, 2.8, 2.1, 2.2, 3.3, 3.2)
)
\hlfunctioncall{ggplot}(values) + \hlfunctioncall{geom_map}(\hlfunctioncall{aes}(map_id = id), map = positions) +
\hlfunctioncall{expand_limits}(positions)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_map1}
\begin{kframe}\begin{alltt}
\hlfunctioncall{ggplot}(values, \hlfunctioncall{aes}(fill = value)) +
\hlfunctioncall{geom_map}(\hlfunctioncall{aes}(map_id = id), map = positions) +
\hlfunctioncall{expand_limits}(positions)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_map2}
\begin{kframe}\begin{alltt}
\hlfunctioncall{ggplot}(values, \hlfunctioncall{aes}(fill = value)) +
\hlfunctioncall{geom_map}(\hlfunctioncall{aes}(map_id = id), map = positions) +
\hlfunctioncall{expand_limits}(positions) + \hlfunctioncall{ylim}(0, 3)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_map3}
\begin{kframe}\begin{alltt}
\hlcomment{# Better example}
crimes <- \hlfunctioncall{data.frame}(state = \hlfunctioncall{tolower}(\hlfunctioncall{rownames}(USArrests)), USArrests)
\hlfunctioncall{library}(reshape2) \hlcomment{# for melt}
crimesm <- \hlfunctioncall{melt}(crimes, id = 1)
\hlfunctioncall{if} (\hlfunctioncall{require}(maps)) \{
states_map <- \hlfunctioncall{map_data}(\hlstring{"state"})
\hlfunctioncall{ggplot}(crimes, \hlfunctioncall{aes}(map_id = state)) + \hlfunctioncall{geom_map}(\hlfunctioncall{aes}(fill = Murder), map = states_map) + \hlfunctioncall{expand_limits}(x = states_map$long, y = states_map$lat)
\hlfunctioncall{last_plot}() + \hlfunctioncall{coord_map}()
\hlfunctioncall{ggplot}(crimesm, \hlfunctioncall{aes}(map_id = state)) + \hlfunctioncall{geom_map}(\hlfunctioncall{aes}(fill = value), map = states_map) + \hlfunctioncall{expand_limits}(x = states_map$long, y = states_map$lat) + \hlfunctioncall{facet_wrap}( ~ variable)
\}
\end{alltt}
{\ttfamily\noindent\itshape\textcolor{messagecolor}{\#\# Loading required package: maps}}\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_map4}
\begin{kframe}\begin{alltt}
\end{alltt}
\end{kframe}
\end{knitrout}
\section{geom\_path}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlcomment{### Name: geom_path}
\hlcomment{### Title: Connect observations in original order}
\hlcomment{### Aliases: geom_path}
\hlcomment{### ** Examples}
\hlcomment{## No test: }
\hlcomment{# Generate data}
\hlfunctioncall{library}(plyr)
myear <- \hlfunctioncall{ddply}(movies, \hlfunctioncall{.}(year), \hlfunctioncall{colwise}(mean, \hlfunctioncall{.}(length, rating)))
p <- \hlfunctioncall{ggplot}(myear, \hlfunctioncall{aes}(length, rating))
p + \hlfunctioncall{geom_path}()
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_path1}
\begin{kframe}\begin{alltt}
\hlcomment{# Add aesthetic mappings}
p + \hlfunctioncall{geom_path}(\hlfunctioncall{aes}(size = year))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_path2}
\begin{kframe}\begin{alltt}
p + \hlfunctioncall{geom_path}(\hlfunctioncall{aes}(colour = year))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_path3}
\begin{kframe}\begin{alltt}
\hlcomment{# Change scale}
p + \hlfunctioncall{geom_path}(\hlfunctioncall{aes}(size = year)) + \hlfunctioncall{scale_size}(range = \hlfunctioncall{c}(1, 3))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_path4}
\begin{kframe}\begin{alltt}
\hlcomment{# Set aesthetics to fixed value}
p + \hlfunctioncall{geom_path}(colour = \hlstring{"green"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_path5}
\begin{kframe}\begin{alltt}
\hlcomment{# Control line join parameters}
df <- \hlfunctioncall{data.frame}(x = 1:3, y = \hlfunctioncall{c}(4, 1, 9))
base <- \hlfunctioncall{ggplot}(df, \hlfunctioncall{aes}(x, y))
base + \hlfunctioncall{geom_path}(size = 10)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_path6}
\begin{kframe}\begin{alltt}
base + \hlfunctioncall{geom_path}(size = 10, lineend = \hlstring{"round"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_path7}
\begin{kframe}\begin{alltt}
base + \hlfunctioncall{geom_path}(size = 10, linejoin = \hlstring{"mitre"}, lineend = \hlstring{"butt"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_path8}
\begin{kframe}\begin{alltt}
\hlcomment{# Use qplot instead}
\hlfunctioncall{qplot}(length, rating, data=myear, geom=\hlstring{"path"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_path9}
\begin{kframe}\begin{alltt}
\hlcomment{# Using economic data:}
\hlcomment{# How is unemployment and personal savings rate related?}
\hlfunctioncall{qplot}(unemploy/pop, psavert, data=economics)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_path10}
\begin{kframe}\begin{alltt}
\hlfunctioncall{qplot}(unemploy/pop, psavert, data=economics, geom=\hlstring{"path"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_path11}
\begin{kframe}\begin{alltt}
\hlfunctioncall{qplot}(unemploy/pop, psavert, data=economics, geom=\hlstring{"path"}, size=\hlfunctioncall{as.numeric}(date))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_path12}
\begin{kframe}\begin{alltt}
\hlcomment{# How is rate of unemployment and length of unemployment?}
\hlfunctioncall{qplot}(unemploy/pop, uempmed, data=economics)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_path13}
\begin{kframe}\begin{alltt}
\hlfunctioncall{qplot}(unemploy/pop, uempmed, data=economics, geom=\hlstring{"path"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_path14}
\begin{kframe}\begin{alltt}
\hlfunctioncall{qplot}(unemploy/pop, uempmed, data=economics, geom=\hlstring{"path"}) +
\hlfunctioncall{geom_point}(data=\hlfunctioncall{head}(economics, 1), colour=\hlstring{"red"}) +
\hlfunctioncall{geom_point}(data=\hlfunctioncall{tail}(economics, 1), colour=\hlstring{"blue"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_path15}
\begin{kframe}\begin{alltt}
\hlfunctioncall{qplot}(unemploy/pop, uempmed, data=economics, geom=\hlstring{"path"}) +
\hlfunctioncall{geom_text}(data=\hlfunctioncall{head}(economics, 1), label=\hlstring{"1967"}, colour=\hlstring{"blue"}) +
\hlfunctioncall{geom_text}(data=\hlfunctioncall{tail}(economics, 1), label=\hlstring{"2007"}, colour=\hlstring{"blue"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_path16}
\begin{kframe}\begin{alltt}
\hlcomment{# geom_path removes missing values on the ends of a line.}
\hlcomment{# use na.rm = T to suppress the warning message}
df <- \hlfunctioncall{data.frame}(
x = 1:5,
y1 = \hlfunctioncall{c}(1, 2, 3, 4, NA),
y2 = \hlfunctioncall{c}(NA, 2, 3, 4, 5),
y3 = \hlfunctioncall{c}(1, 2, NA, 4, 5),
y4 = \hlfunctioncall{c}(1, 2, 3, 4, 5))
\hlfunctioncall{qplot}(x, y1, data = df, geom = \hlfunctioncall{c}(\hlstring{"point"},\hlstring{"line"}))
\end{alltt}
{\ttfamily\noindent\textcolor{warningcolor}{\#\# Warning: Removed 1 rows containing missing values (geom\_point).}}
{\ttfamily\noindent\textcolor{warningcolor}{\#\# Warning: Removed 1 rows containing missing values (geom\_path).}}\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_path17}
\begin{kframe}\begin{alltt}
\hlfunctioncall{qplot}(x, y2, data = df, geom = \hlfunctioncall{c}(\hlstring{"point"},\hlstring{"line"}))
\end{alltt}
{\ttfamily\noindent\textcolor{warningcolor}{\#\# Warning: Removed 1 rows containing missing values (geom\_point).}}
{\ttfamily\noindent\textcolor{warningcolor}{\#\# Warning: Removed 1 rows containing missing values (geom\_path).}}\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_path18}
\begin{kframe}\begin{alltt}
\hlfunctioncall{qplot}(x, y3, data = df, geom = \hlfunctioncall{c}(\hlstring{"point"},\hlstring{"line"}))
\end{alltt}
{\ttfamily\noindent\textcolor{warningcolor}{\#\# Warning: Removed 1 rows containing missing values (geom\_point).}}\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_path19}
\begin{kframe}\begin{alltt}
\hlfunctioncall{qplot}(x, y4, data = df, geom = \hlfunctioncall{c}(\hlstring{"point"},\hlstring{"line"}))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_path20}
\begin{kframe}\begin{alltt}
\hlcomment{# Setting line type vs colour/size}
\hlcomment{# Line type needs to be applied to a line as a whole, so it can}
\hlcomment{# not be used with colour or size that vary across a line}
x <- \hlfunctioncall{seq}(0.01, .99, length=100)
df <- \hlfunctioncall{data.frame}(x = \hlfunctioncall{rep}(x, 2), y = \hlfunctioncall{c}(\hlfunctioncall{qlogis}(x), 2 * \hlfunctioncall{qlogis}(x)), group = \hlfunctioncall{rep}(\hlfunctioncall{c}(\hlstring{"a"},\hlstring{"b"}), each=100))
p <- \hlfunctioncall{ggplot}(df, \hlfunctioncall{aes}(x=x, y=y, group=group))
\hlcomment{# Should work}
p + \hlfunctioncall{geom_line}(linetype = 2)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_path21}
\begin{kframe}\begin{alltt}
p + \hlfunctioncall{geom_line}(\hlfunctioncall{aes}(colour = group), linetype = 2)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_path22}
\begin{kframe}\begin{alltt}
p + \hlfunctioncall{geom_line}(\hlfunctioncall{aes}(colour = x))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_path23}
\begin{kframe}\begin{alltt}
\hlcomment{# Should fail}
\hlfunctioncall{should_stop}(p + \hlfunctioncall{geom_line}(\hlfunctioncall{aes}(colour = x), linetype=2))
\hlcomment{# Use the arrow parameter to add an arrow to the line}
\hlcomment{# See ?grid::arrow for more details}
\hlfunctioncall{library}(grid)
c <- \hlfunctioncall{ggplot}(economics, \hlfunctioncall{aes}(x = date, y = pop))
\hlcomment{# Arrow defaults to "last"}
c + \hlfunctioncall{geom_path}(arrow = \hlfunctioncall{arrow}())
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_path24}
\begin{kframe}\begin{alltt}
c + \hlfunctioncall{geom_path}(arrow = \hlfunctioncall{arrow}(angle = 15, ends = \hlstring{"both"}, length = \hlfunctioncall{unit}(0.6, \hlstring{"inches"})))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_path25}
\begin{kframe}\begin{alltt}
\hlcomment{## End(No test)}
\end{alltt}
\end{kframe}
\end{knitrout}
\section{geom\_point}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlcomment{### Name: geom_point}
\hlcomment{### Title: Points, as for a scatterplot}
\hlcomment{### Aliases: geom_point}
\hlcomment{### ** Examples}
\hlcomment{## No test: }
p <- \hlfunctioncall{ggplot}(mtcars, \hlfunctioncall{aes}(wt, mpg))
p + \hlfunctioncall{geom_point}()
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_point1}
\begin{kframe}\begin{alltt}
\hlcomment{# Add aesthetic mappings}
p + \hlfunctioncall{geom_point}(\hlfunctioncall{aes}(colour = qsec))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_point2}
\begin{kframe}\begin{alltt}
p + \hlfunctioncall{geom_point}(\hlfunctioncall{aes}(alpha = qsec))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_point3}
\begin{kframe}\begin{alltt}
p + \hlfunctioncall{geom_point}(\hlfunctioncall{aes}(colour = \hlfunctioncall{factor}(cyl)))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_point4}
\begin{kframe}\begin{alltt}
p + \hlfunctioncall{geom_point}(\hlfunctioncall{aes}(shape = \hlfunctioncall{factor}(cyl)))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_point5}
\begin{kframe}\begin{alltt}
p + \hlfunctioncall{geom_point}(\hlfunctioncall{aes}(size = qsec))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_point6}
\begin{kframe}\begin{alltt}
\hlcomment{# Change scales}
p + \hlfunctioncall{geom_point}(\hlfunctioncall{aes}(colour = cyl)) + \hlfunctioncall{scale_colour_gradient}(low = \hlstring{"blue"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_point7}
\begin{kframe}\begin{alltt}
p + \hlfunctioncall{geom_point}(\hlfunctioncall{aes}(size = qsec)) + \hlfunctioncall{scale_area}()
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_point8}
\begin{kframe}\begin{alltt}
p + \hlfunctioncall{geom_point}(\hlfunctioncall{aes}(shape = \hlfunctioncall{factor}(cyl))) + \hlfunctioncall{scale_shape}(solid = FALSE)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_point9}
\begin{kframe}\begin{alltt}
\hlcomment{# Set aesthetics to fixed value}
p + \hlfunctioncall{geom_point}(colour = \hlstring{"red"}, size = 3)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_point10}
\begin{kframe}\begin{alltt}
\hlfunctioncall{qplot}(wt, mpg, data = mtcars, colour = \hlfunctioncall{I}(\hlstring{"red"}), size = \hlfunctioncall{I}(3))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_point11}
\begin{kframe}\begin{alltt}
\hlcomment{# Varying alpha is useful for large datasets}
d <- \hlfunctioncall{ggplot}(diamonds, \hlfunctioncall{aes}(carat, price))
d + \hlfunctioncall{geom_point}(alpha = 1/10)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_point12}
\begin{kframe}\begin{alltt}
d + \hlfunctioncall{geom_point}(alpha = 1/20)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_point13}
\begin{kframe}\begin{alltt}
d + \hlfunctioncall{geom_point}(alpha = 1/100)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_point14}
\begin{kframe}\begin{alltt}
\hlcomment{# You can create interesting shapes by layering multiple points of}
\hlcomment{# different sizes}
p <- \hlfunctioncall{ggplot}(mtcars, \hlfunctioncall{aes}(mpg, wt))
p + \hlfunctioncall{geom_point}(colour=\hlstring{"grey50"}, size = 4) + \hlfunctioncall{geom_point}(\hlfunctioncall{aes}(colour = cyl))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_point15}
\begin{kframe}\begin{alltt}
p + \hlfunctioncall{aes}(shape = \hlfunctioncall{factor}(cyl)) +
\hlfunctioncall{geom_point}(\hlfunctioncall{aes}(colour = \hlfunctioncall{factor}(cyl)), size = 4) +
\hlfunctioncall{geom_point}(colour=\hlstring{"grey90"}, size = 1.5)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_point16}
\begin{kframe}\begin{alltt}
p + \hlfunctioncall{geom_point}(colour=\hlstring{"black"}, size = 4.5) +
\hlfunctioncall{geom_point}(colour=\hlstring{"pink"}, size = 4) +
\hlfunctioncall{geom_point}(\hlfunctioncall{aes}(shape = \hlfunctioncall{factor}(cyl)))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_point17}
\begin{kframe}\begin{alltt}
\hlcomment{# These extra layers don't usually appear in the legend, but we can}
\hlcomment{# force their inclusion}
p + \hlfunctioncall{geom_point}(colour=\hlstring{"black"}, size = 4.5, show_guide = TRUE) +
\hlfunctioncall{geom_point}(colour=\hlstring{"pink"}, size = 4, show_guide = TRUE) +
\hlfunctioncall{geom_point}(\hlfunctioncall{aes}(shape = \hlfunctioncall{factor}(cyl)))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_point18}
\begin{kframe}\begin{alltt}
\hlcomment{# Transparent points:}
\hlfunctioncall{qplot}(mpg, wt, data = mtcars, size = \hlfunctioncall{I}(5), alpha = \hlfunctioncall{I}(0.2))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_point19}
\begin{kframe}\begin{alltt}
\hlcomment{# geom_point warns when missing values have been dropped from the data set}
\hlcomment{# and not plotted, you can turn this off by setting na.rm = TRUE}
mtcars2 <- \hlfunctioncall{transform}(mtcars, mpg = \hlfunctioncall{ifelse}(\hlfunctioncall{runif}(32) < 0.2, NA, mpg))
\hlfunctioncall{qplot}(wt, mpg, data = mtcars2)
\end{alltt}
{\ttfamily\noindent\textcolor{warningcolor}{\#\# Warning: Removed 11 rows containing missing values (geom\_point).}}\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_point20}
\begin{kframe}\begin{alltt}
\hlfunctioncall{qplot}(wt, mpg, data = mtcars2, na.rm = TRUE)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_point21}
\begin{kframe}\begin{alltt}
\hlcomment{# Use qplot instead}
\hlfunctioncall{qplot}(wt, mpg, data = mtcars)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_point22}
\begin{kframe}\begin{alltt}
\hlfunctioncall{qplot}(wt, mpg, data = mtcars, colour = \hlfunctioncall{factor}(cyl))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_point23}
\begin{kframe}\begin{alltt}
\hlfunctioncall{qplot}(wt, mpg, data = mtcars, colour = \hlfunctioncall{I}(\hlstring{"red"}))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_point24}
\begin{kframe}\begin{alltt}
\hlcomment{## End(No test)}
\end{alltt}
\end{kframe}
\end{knitrout}
\section{geom\_pointrange}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlcomment{### Name: geom_pointrange}
\hlcomment{### Title: An interval represented by a vertical line, with a point in the}
\hlcomment{### middle.}
\hlcomment{### Aliases: geom_pointrange}
\hlcomment{### ** Examples}
\hlcomment{# See geom_linerange for examples}
\end{alltt}
\end{kframe}
\end{knitrout}
\section{geom\_polygon}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlcomment{### Name: geom_polygon}
\hlcomment{### Title: Polygon, a filled path.}
\hlcomment{### Aliases: geom_polygon}
\hlcomment{### ** Examples}
\hlcomment{# When using geom_polygon, you will typically need two data frames:}
\hlcomment{# one contains the coordinates of each polygon (positions), and the}
\hlcomment{# other the values associated with each polygon (values). An id}
\hlcomment{# variable links the two together}
ids <- \hlfunctioncall{factor}(\hlfunctioncall{c}(\hlstring{"1.1"}, \hlstring{"2.1"}, \hlstring{"1.2"}, \hlstring{"2.2"}, \hlstring{"1.3"}, \hlstring{"2.3"}))
values <- \hlfunctioncall{data.frame}(
id = ids,
value = \hlfunctioncall{c}(3, 3.1, 3.1, 3.2, 3.15, 3.5)
)
positions <- \hlfunctioncall{data.frame}(
id = \hlfunctioncall{rep}(ids, each = 4),
x = \hlfunctioncall{c}(2, 1, 1.1, 2.2, 1, 0, 0.3, 1.1, 2.2, 1.1, 1.2, 2.5, 1.1, 0.3,
0.5, 1.2, 2.5, 1.2, 1.3, 2.7, 1.2, 0.5, 0.6, 1.3),
y = \hlfunctioncall{c}(-0.5, 0, 1, 0.5, 0, 0.5, 1.5, 1, 0.5, 1, 2.1, 1.7, 1, 1.5,
2.2, 2.1, 1.7, 2.1, 3.2, 2.8, 2.1, 2.2, 3.3, 3.2)
)
\hlcomment{# Currently we need to manually merge the two together}
datapoly <- \hlfunctioncall{merge}(values, positions, by=\hlfunctioncall{c}(\hlstring{"id"}))
(p <- \hlfunctioncall{ggplot}(datapoly, \hlfunctioncall{aes}(x=x, y=y)) + \hlfunctioncall{geom_polygon}(\hlfunctioncall{aes}(fill=value, group=id)))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_polygon1}
\begin{kframe}\begin{alltt}
\hlcomment{# Which seems like a lot of work, but then it's easy to add on}
\hlcomment{# other features in this coordinate system, e.g.:}
stream <- \hlfunctioncall{data.frame}(
x = \hlfunctioncall{cumsum}(\hlfunctioncall{runif}(50, max = 0.1)),
y = \hlfunctioncall{cumsum}(\hlfunctioncall{runif}(50,max = 0.1))
)
p + \hlfunctioncall{geom_line}(data = stream, colour=\hlstring{"grey30"}, size = 5)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_polygon2}
\begin{kframe}\begin{alltt}
\hlcomment{# And if the positions are in longitude and latitude, you can use}
\hlcomment{# coord_map to produce different map projections.}
\end{alltt}
\end{kframe}
\end{knitrout}
\section{geom\_quantile}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlcomment{### Name: geom_quantile}
\hlcomment{### Title: Add quantile lines from a quantile regression.}
\hlcomment{### Aliases: geom_quantile}
\hlcomment{### ** Examples}
\hlcomment{# See stat_quantile for examples}
\end{alltt}
\end{kframe}
\end{knitrout}
\section{geom\_raster}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlcomment{### Name: geom_raster}
\hlcomment{### Title: High-performance rectangular tiling.}
\hlcomment{### Aliases: geom_raster}
\hlcomment{### ** Examples}
\hlcomment{## No test: }
\hlcomment{# Generate data}
pp <- \hlfunctioncall{function} (n,r=4) \{
x <- \hlfunctioncall{seq}(-r*pi, r*pi, len=n)
df <- \hlfunctioncall{expand.grid}(x=x, y=x)
df$r <- \hlfunctioncall{sqrt}(df$x^2 + df$y^2)
df$z <- \hlfunctioncall{cos}(df$r^2)*\hlfunctioncall{exp}(-df$r/6)
df
\}
\hlfunctioncall{qplot}(x, y, data = \hlfunctioncall{pp}(20), fill = z, geom = \hlstring{"raster"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_raster1}
\begin{kframe}\begin{alltt}
\hlcomment{# Interpolation worsens the apperance of this plot, but can help when}
\hlcomment{# rendering images.}
\hlfunctioncall{qplot}(x, y, data = \hlfunctioncall{pp}(20), fill = z, geom = \hlstring{"raster"}, interpolate = TRUE)
\hlcomment{# For the special cases where it is applicable, geom_raster is much}
\hlcomment{# faster than geom_tile:}
pp200 <- \hlfunctioncall{pp}(200)
base <- \hlfunctioncall{ggplot}(pp200, \hlfunctioncall{aes}(x, y, fill = z))
\hlfunctioncall{benchplot}(base + \hlfunctioncall{geom_raster}())
\end{alltt}
\begin{verbatim}
## step user.self sys.self elapsed
## 1 construct 0.008 0.000 0.010
## 2 build 1.164 0.020 1.189
## 3 render 0.420 0.016 0.438
## 4 draw 0.116 0.000 0.116
## 5 TOTAL 1.708 0.036 1.753
\end{verbatim}
\begin{alltt}
\hlfunctioncall{benchplot}(base + \hlfunctioncall{geom_tile}())
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_raster2}
\begin{kframe}\begin{verbatim}
## step user.self sys.self elapsed
## 1 construct 0.008 0.000 0.009
## 2 build 1.184 0.012 1.199
## 3 render 0.580 0.024 0.609
## 4 draw 0.248 0.000 0.250
## 5 TOTAL 2.020 0.036 2.067
\end{verbatim}
\begin{alltt}
\hlcomment{# justification}
df <- \hlfunctioncall{expand.grid}(x = 0:5, y = 0:5)
df$z <- \hlfunctioncall{runif}(\hlfunctioncall{nrow}(df))
\hlcomment{# default is compatible with geom_tile()}
\hlfunctioncall{ggplot}(df, \hlfunctioncall{aes}(x, y, fill = z)) + \hlfunctioncall{geom_raster}()
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_raster3}
\begin{kframe}\begin{alltt}
\hlcomment{# zero padding}
\hlfunctioncall{ggplot}(df, \hlfunctioncall{aes}(x, y, fill = z)) + \hlfunctioncall{geom_raster}(hjust = 0, vjust = 0)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_raster4}
\begin{kframe}\begin{alltt}
\hlcomment{## End(No test)}
\end{alltt}
\end{kframe}
\end{knitrout}
\section{geom\_rect}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlcomment{### Name: geom_rect}
\hlcomment{### Title: 2d rectangles.}
\hlcomment{### Aliases: geom_rect}
\hlcomment{### ** Examples}
df <- \hlfunctioncall{data.frame}(
x = \hlfunctioncall{sample}(10, 20, replace = TRUE),
y = \hlfunctioncall{sample}(10, 20, replace = TRUE)
)
\hlfunctioncall{ggplot}(df, \hlfunctioncall{aes}(xmin = x, xmax = x + 1, ymin = y, ymax = y + 2)) +
\hlfunctioncall{geom_rect}()
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_rect}
\begin{kframe}\begin{alltt}
\end{alltt}
\end{kframe}
\end{knitrout}
\section{geom\_ribbon}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlcomment{### Name: geom_ribbon}
\hlcomment{### Title: Ribbons, y range with continuous x values.}
\hlcomment{### Aliases: geom_ribbon}
\hlcomment{### ** Examples}
\hlcomment{## No test: }
\hlcomment{# Generate data}
huron <- \hlfunctioncall{data.frame}(year = 1875:1972, level = \hlfunctioncall{as.vector}(LakeHuron))
\hlfunctioncall{library}(plyr) \hlcomment{# to access round_any}
huron$decade <- \hlfunctioncall{round_any}(huron$year, 10, floor)
h <- \hlfunctioncall{ggplot}(huron, \hlfunctioncall{aes}(x=year))
h + \hlfunctioncall{geom_ribbon}(\hlfunctioncall{aes}(ymin=0, ymax=level))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_ribbon1}
\begin{kframe}\begin{alltt}
h + \hlfunctioncall{geom_area}(\hlfunctioncall{aes}(y = level))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_ribbon2}
\begin{kframe}\begin{alltt}
\hlcomment{# Add aesthetic mappings}
h + \hlfunctioncall{geom_ribbon}(\hlfunctioncall{aes}(ymin=level-1, ymax=level+1))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_ribbon3}
\begin{kframe}\begin{alltt}
h + \hlfunctioncall{geom_ribbon}(\hlfunctioncall{aes}(ymin=level-1, ymax=level+1)) + \hlfunctioncall{geom_line}(\hlfunctioncall{aes}(y=level))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_ribbon4}
\begin{kframe}\begin{alltt}
\hlcomment{# Take out some values in the middle for an example of NA handling}
huron[huron$year > 1900 & huron$year < 1910, \hlstring{"level"}] <- NA
h <- \hlfunctioncall{ggplot}(huron, \hlfunctioncall{aes}(x=year))
h + \hlfunctioncall{geom_ribbon}(\hlfunctioncall{aes}(ymin=level-1, ymax=level+1)) + \hlfunctioncall{geom_line}(\hlfunctioncall{aes}(y=level))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_ribbon5}
\begin{kframe}\begin{alltt}
\hlcomment{# Another data set, with multiple y's for each x}
m <- \hlfunctioncall{ggplot}(movies, \hlfunctioncall{aes}(y=votes, x=year))
(m <- m + \hlfunctioncall{geom_point}())
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_ribbon6}
\begin{kframe}\begin{alltt}
\hlcomment{# The default summary isn't that useful}
m + \hlfunctioncall{stat_summary}(geom=\hlstring{"ribbon"}, fun.ymin=\hlstring{"min"}, fun.ymax=\hlstring{"max"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_ribbon7}
\begin{kframe}\begin{alltt}
m + \hlfunctioncall{stat_summary}(geom=\hlstring{"ribbon"}, fun.data=\hlstring{"median_hilow"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_ribbon8}
\begin{kframe}\begin{alltt}
\hlcomment{# Use qplot instead}
\hlfunctioncall{qplot}(year, level, data=huron, geom=\hlfunctioncall{c}(\hlstring{"area"}, \hlstring{"line"}))
\end{alltt}
{\ttfamily\noindent\textcolor{warningcolor}{\#\# Warning: Removed 9 rows containing missing values (position\_stack).}}\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_ribbon9}
\begin{kframe}\begin{alltt}
\hlcomment{## End(No test)}
\end{alltt}
\end{kframe}
\end{knitrout}
\section{geom\_rug}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlcomment{### Name: geom_rug}
\hlcomment{### Title: Marginal rug plots.}
\hlcomment{### Aliases: geom_rug}
\hlcomment{### ** Examples}
p <- \hlfunctioncall{ggplot}(mtcars, \hlfunctioncall{aes}(x=wt, y=mpg))
p + \hlfunctioncall{geom_point}()
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_rug1}
\begin{kframe}\begin{alltt}
p + \hlfunctioncall{geom_point}() + \hlfunctioncall{geom_rug}()
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_rug2}
\begin{kframe}\begin{alltt}
p + \hlfunctioncall{geom_point}() + \hlfunctioncall{geom_rug}(sides=\hlstring{"b"}) # Rug on bottom only
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_rug3}
\begin{kframe}\begin{alltt}
p + \hlfunctioncall{geom_point}() + \hlfunctioncall{geom_rug}(sides=\hlstring{"trbl"}) # All four sides
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_rug4}
\begin{kframe}\begin{alltt}
p + \hlfunctioncall{geom_point}() + \hlfunctioncall{geom_rug}(position=\hlstring{'jitter'})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_rug5}
\begin{kframe}\begin{alltt}
\end{alltt}
\end{kframe}
\end{knitrout}
\section{geom\_segment}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlcomment{### Name: geom_segment}
\hlcomment{### Title: Single line segments.}
\hlcomment{### Aliases: geom_segment}
\hlcomment{### ** Examples}
\hlfunctioncall{library}(grid) \hlcomment{# needed for arrow function}
p <- \hlfunctioncall{ggplot}(seals, \hlfunctioncall{aes}(x = long, y = lat))
(p <- p + \hlfunctioncall{geom_segment}(\hlfunctioncall{aes}(xend = long + delta_long, yend = lat + delta_lat), arrow = \hlfunctioncall{arrow}(length = \hlfunctioncall{unit}(0.1,\hlstring{"cm"}))))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_segment1}
\begin{kframe}\begin{alltt}
\hlfunctioncall{if} (\hlfunctioncall{require}(\hlstring{"maps"})) \{
xlim <- \hlfunctioncall{range}(seals$long)
ylim <- \hlfunctioncall{range}(seals$lat)
usamap <- \hlfunctioncall{data.frame}(\hlfunctioncall{map}(\hlstring{"world"}, xlim = xlim, ylim = ylim, plot =
FALSE)[\hlfunctioncall{c}(\hlstring{"x"},\hlstring{"y"})])
usamap <- \hlfunctioncall{rbind}(usamap, NA, \hlfunctioncall{data.frame}(\hlfunctioncall{map}(\hlstring{'state'}, xlim = xlim, ylim
= ylim, plot = FALSE)[\hlfunctioncall{c}(\hlstring{"x"},\hlstring{"y"})]))
\hlfunctioncall{names}(usamap) <- \hlfunctioncall{c}(\hlstring{"long"}, \hlstring{"lat"})
p + \hlfunctioncall{geom_path}(data = usamap) + \hlfunctioncall{scale_x_continuous}(limits = xlim)
\}
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_segment2}
\begin{kframe}\begin{alltt}
\hlcomment{# You can also use geom_segment to recreate plot(type = "h") :}
counts <- \hlfunctioncall{as.data.frame}(\hlfunctioncall{table}(x = \hlfunctioncall{rpois}(100,5)))
counts$x <- \hlfunctioncall{as.numeric}(\hlfunctioncall{as.character}(counts$x))
\hlfunctioncall{with}(counts, \hlfunctioncall{plot}(x, Freq, type = \hlstring{"h"}, lwd = 10))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_segment3}
\begin{kframe}\begin{alltt}
\hlfunctioncall{qplot}(x, Freq, data = counts, geom = \hlstring{"segment"},
yend = 0, xend = x, size = \hlfunctioncall{I}(10))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_segment4}
\begin{kframe}\begin{alltt}
\hlcomment{# Adding line segments}
\hlfunctioncall{library}(grid) \hlcomment{# needed for arrow function}
b <- \hlfunctioncall{ggplot}(mtcars, \hlfunctioncall{aes}(wt, mpg)) + \hlfunctioncall{geom_point}()
b + \hlfunctioncall{geom_segment}(\hlfunctioncall{aes}(x = 2, y = 15, xend = 2, yend = 25))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_segment5}
\begin{kframe}\begin{alltt}
b + \hlfunctioncall{geom_segment}(\hlfunctioncall{aes}(x = 2, y = 15, xend = 3, yend = 15))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_segment6}
\begin{kframe}\begin{alltt}
b + \hlfunctioncall{geom_segment}(\hlfunctioncall{aes}(x = 5, y = 30, xend = 3.5, yend = 25), arrow = \hlfunctioncall{arrow}(length = \hlfunctioncall{unit}(0.5, \hlstring{"cm"})))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_segment7}
\begin{kframe}\begin{alltt}
\end{alltt}
\end{kframe}
\end{knitrout}
\section{geom\_smooth}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlcomment{### Name: geom_smooth}
\hlcomment{### Title: Add a smoothed conditional mean.}
\hlcomment{### Aliases: geom_smooth}
\hlcomment{### ** Examples}
\hlcomment{# See stat_smooth for examples of using built in model fitting}
\hlcomment{# if you need some more flexible, this example shows you how to}
\hlcomment{# plot the fits from any model of your choosing}
\hlfunctioncall{qplot}(wt, mpg, data=mtcars, colour=\hlfunctioncall{factor}(cyl))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_smooth1}
\begin{kframe}\begin{alltt}
model <- \hlfunctioncall{lm}(mpg ~ wt + \hlfunctioncall{factor}(cyl), data=mtcars)
grid <- \hlfunctioncall{with}(mtcars, \hlfunctioncall{expand.grid}(
wt = \hlfunctioncall{seq}(\hlfunctioncall{min}(wt), \hlfunctioncall{max}(wt), length = 20),
cyl = \hlfunctioncall{levels}(\hlfunctioncall{factor}(cyl))
))
grid$mpg <- stats::\hlfunctioncall{predict}(model, newdata=grid)
\hlfunctioncall{qplot}(wt, mpg, data=mtcars, colour=\hlfunctioncall{factor}(cyl)) + \hlfunctioncall{geom_line}(data=grid)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_smooth2}
\begin{kframe}\begin{alltt}
\hlcomment{# or with standard errors}
err <- stats::\hlfunctioncall{predict}(model, newdata=grid, se = TRUE)
grid$ucl <- err$fit + 1.96 * err$se.fit
grid$lcl <- err$fit - 1.96 * err$se.fit
\hlfunctioncall{qplot}(wt, mpg, data=mtcars, colour=\hlfunctioncall{factor}(cyl)) +
\hlfunctioncall{geom_smooth}(\hlfunctioncall{aes}(ymin = lcl, ymax = ucl), data=grid, stat=\hlstring{"identity"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_smooth3}
\begin{kframe}\begin{alltt}
\end{alltt}
\end{kframe}
\end{knitrout}
\section{geom\_step}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlcomment{### Name: geom_step}
\hlcomment{### Title: Connect observations by stairs.}
\hlcomment{### Aliases: geom_step}
\hlcomment{### ** Examples}
\hlcomment{# Simple quantiles/ECDF from examples(plot)}
x <- \hlfunctioncall{sort}(\hlfunctioncall{rnorm}(47))
\hlfunctioncall{qplot}(\hlfunctioncall{seq_along}(x), x, geom=\hlstring{"step"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_step1}
\begin{kframe}\begin{alltt}
\hlcomment{# Steps go horizontally, then vertically (default)}
\hlfunctioncall{qplot}(\hlfunctioncall{seq_along}(x), x, geom=\hlstring{"step"}, direction = \hlstring{"hv"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_step2}
\begin{kframe}\begin{alltt}
\hlfunctioncall{plot}(x, type = \hlstring{"s"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_step3}
\begin{kframe}\begin{alltt}
\hlcomment{# Steps go vertically, then horizontally}
\hlfunctioncall{qplot}(\hlfunctioncall{seq_along}(x), x, geom=\hlstring{"step"}, direction = \hlstring{"vh"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_step4}
\begin{kframe}\begin{alltt}
\hlfunctioncall{plot}(x, type = \hlstring{"S"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_step5}
\begin{kframe}\begin{alltt}
\hlcomment{# Also works with other aesthetics}
df <- \hlfunctioncall{data.frame}(
x = \hlfunctioncall{sort}(\hlfunctioncall{rnorm}(50)),
trt = \hlfunctioncall{sample}(\hlfunctioncall{c}(\hlstring{"a"}, \hlstring{"b"}), 50, rep = TRUE)
)
\hlfunctioncall{qplot}(\hlfunctioncall{seq_along}(x), x, data = df, geom=\hlstring{"step"}, colour = trt)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_step6}
\begin{kframe}\begin{alltt}
\end{alltt}
\end{kframe}
\end{knitrout}
\section{geom\_text}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlcomment{### Name: geom_text}
\hlcomment{### Title: Textual annotations.}
\hlcomment{### Aliases: geom_text}
\hlcomment{### ** Examples}
\hlcomment{## No test: }
p <- \hlfunctioncall{ggplot}(mtcars, \hlfunctioncall{aes}(x=wt, y=mpg, label=\hlfunctioncall{rownames}(mtcars)))
p + \hlfunctioncall{geom_text}()
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_text1}
\begin{kframe}\begin{alltt}
\hlcomment{# Change size of the label}
p + \hlfunctioncall{geom_text}(size=10)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_text2}
\begin{kframe}\begin{alltt}
p <- p + \hlfunctioncall{geom_point}()
\hlcomment{# Set aesthetics to fixed value}
p + \hlfunctioncall{geom_text}()
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_text3}
\begin{kframe}\begin{alltt}
p + \hlfunctioncall{geom_point}() + \hlfunctioncall{geom_text}(hjust=0, vjust=0)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_text4}
\begin{kframe}\begin{alltt}
p + \hlfunctioncall{geom_point}() + \hlfunctioncall{geom_text}(angle = 45)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_text5}
\begin{kframe}\begin{alltt}
\hlcomment{# Add aesthetic mappings}
p + \hlfunctioncall{geom_text}(\hlfunctioncall{aes}(colour=\hlfunctioncall{factor}(cyl)))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_text6}
\begin{kframe}\begin{alltt}
p + \hlfunctioncall{geom_text}(\hlfunctioncall{aes}(colour=\hlfunctioncall{factor}(cyl))) + \hlfunctioncall{scale_colour_discrete}(l=40)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_text7}
\begin{kframe}\begin{alltt}
p + \hlfunctioncall{geom_text}(\hlfunctioncall{aes}(size=wt))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_text8}
\begin{kframe}\begin{alltt}
p + \hlfunctioncall{geom_text}(\hlfunctioncall{aes}(size=wt)) + \hlfunctioncall{scale_size}(range=\hlfunctioncall{c}(3,6))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_text9}
\begin{kframe}\begin{alltt}
\hlcomment{# You can display expressions by setting parse = TRUE. The}
\hlcomment{# details of the display are described in ?plotmath, but note that}
\hlcomment{# geom_text uses strings, not expressions.}
p + \hlfunctioncall{geom_text}(\hlfunctioncall{aes}(label = \hlfunctioncall{paste}(wt, \hlstring{"^("}, cyl, \hlstring{")"}, sep = \hlstring{""})),
parse = TRUE)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_text10}
\begin{kframe}\begin{alltt}
\hlcomment{# Add an annotation not from a variable source}
c <- \hlfunctioncall{ggplot}(mtcars, \hlfunctioncall{aes}(wt, mpg)) + \hlfunctioncall{geom_point}()
c + \hlfunctioncall{geom_text}(data = NULL, x = 5, y = 30, label = \hlstring{"plot mpg vs. wt"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_text11}
\begin{kframe}\begin{alltt}
\hlcomment{# Or, you can use annotate}
c + \hlfunctioncall{annotate}(\hlstring{"text"}, label = \hlstring{"plot mpg vs. wt"}, x = 2, y = 15, size = 8, colour = \hlstring{"red"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_text12}
\begin{kframe}\begin{alltt}
\hlcomment{# Use qplot instead}
\hlfunctioncall{qplot}(wt, mpg, data = mtcars, label = \hlfunctioncall{rownames}(mtcars),
geom=\hlfunctioncall{c}(\hlstring{"point"}, \hlstring{"text"}))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_text13}
\begin{kframe}\begin{alltt}
\hlfunctioncall{qplot}(wt, mpg, data = mtcars, label = \hlfunctioncall{rownames}(mtcars), size = wt) +
\hlfunctioncall{geom_text}(colour = \hlstring{"red"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_text14}
\begin{kframe}\begin{alltt}
\hlcomment{# You can specify family, fontface and lineheight}
p <- \hlfunctioncall{ggplot}(mtcars, \hlfunctioncall{aes}(x=wt, y=mpg, label=\hlfunctioncall{rownames}(mtcars)))
p + \hlfunctioncall{geom_text}(fontface=3)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_text15}
\begin{kframe}\begin{alltt}
p + \hlfunctioncall{geom_text}(\hlfunctioncall{aes}(fontface=am+1))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_text16}
\begin{kframe}\begin{alltt}
p + \hlfunctioncall{geom_text}(\hlfunctioncall{aes}(family=\hlfunctioncall{c}(\hlstring{"serif"}, \hlstring{"mono"})[am+1]))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_text17}
\begin{kframe}\begin{alltt}
\hlcomment{## End(No test)}
\end{alltt}
\end{kframe}
\end{knitrout}
\section{geom\_tile}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlcomment{### Name: geom_tile}
\hlcomment{### Title: Tile plane with rectangles.}
\hlcomment{### Aliases: geom_tile}
\hlcomment{### ** Examples}
\hlcomment{## No test: }
\hlcomment{# Generate data}
pp <- \hlfunctioncall{function} (n,r=4) \{
x <- \hlfunctioncall{seq}(-r*pi, r*pi, len=n)
df <- \hlfunctioncall{expand.grid}(x=x, y=x)
df$r <- \hlfunctioncall{sqrt}(df$x^2 + df$y^2)
df$z <- \hlfunctioncall{cos}(df$r^2)*\hlfunctioncall{exp}(-df$r/6)
df
\}
p <- \hlfunctioncall{ggplot}(\hlfunctioncall{pp}(20), \hlfunctioncall{aes}(x=x,y=y))
p + \hlfunctioncall{geom_tile}() \hlcomment{#pretty useless!}
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_tile1}
\begin{kframe}\begin{alltt}
\hlcomment{# Add aesthetic mappings}
p + \hlfunctioncall{geom_tile}(\hlfunctioncall{aes}(fill=z))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_tile2}
\begin{kframe}\begin{alltt}
\hlcomment{# Change scale}
p + \hlfunctioncall{geom_tile}(\hlfunctioncall{aes}(fill=z)) + \hlfunctioncall{scale_fill_gradient}(low=\hlstring{"green"}, high=\hlstring{"red"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_tile3}
\begin{kframe}\begin{alltt}
\hlcomment{# Use qplot instead}
\hlfunctioncall{qplot}(x, y, data=\hlfunctioncall{pp}(20), geom=\hlstring{"tile"}, fill=z)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_tile4}
\begin{kframe}\begin{alltt}
\hlfunctioncall{qplot}(x, y, data=\hlfunctioncall{pp}(100), geom=\hlstring{"tile"}, fill=z)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_tile5}
\begin{kframe}\begin{alltt}
\hlcomment{# Missing values}
p <- \hlfunctioncall{ggplot}(\hlfunctioncall{pp}(20)[\hlfunctioncall{sample}(20*20, size=200),], \hlfunctioncall{aes}(x=x,y=y,fill=z))
p + \hlfunctioncall{geom_tile}()
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_tile6}
\begin{kframe}\begin{alltt}
\hlcomment{# Input that works with image}
\hlfunctioncall{image}(\hlfunctioncall{t}(volcano)[\hlfunctioncall{ncol}(volcano):1,])
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_tile7}
\begin{kframe}\begin{alltt}
\hlfunctioncall{library}(reshape2) \hlcomment{# for melt}
\hlfunctioncall{ggplot}(\hlfunctioncall{melt}(volcano), \hlfunctioncall{aes}(x=Var1, y=Var2, fill=value)) + \hlfunctioncall{geom_tile}()
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_tile8}
\begin{kframe}\begin{alltt}
\hlcomment{# inspired by the image-density plots of Ken Knoblauch}
cars <- \hlfunctioncall{ggplot}(mtcars, \hlfunctioncall{aes}(y=\hlfunctioncall{factor}(cyl), x=mpg))
cars + \hlfunctioncall{geom_point}()
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_tile9}
\begin{kframe}\begin{alltt}
cars + \hlfunctioncall{stat_bin}(\hlfunctioncall{aes}(fill=..count..), geom=\hlstring{"tile"}, binwidth=3, position=\hlstring{"identity"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_tile10}
\begin{kframe}\begin{alltt}
cars + \hlfunctioncall{stat_bin}(\hlfunctioncall{aes}(fill=..density..), geom=\hlstring{"tile"}, binwidth=3, position=\hlstring{"identity"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_tile11}
\begin{kframe}\begin{alltt}
cars + \hlfunctioncall{stat_density}(\hlfunctioncall{aes}(fill=..density..), geom=\hlstring{"tile"}, position=\hlstring{"identity"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_tile12}
\begin{kframe}\begin{alltt}
cars + \hlfunctioncall{stat_density}(\hlfunctioncall{aes}(fill=..count..), geom=\hlstring{"tile"}, position=\hlstring{"identity"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_tile13}
\begin{kframe}\begin{alltt}
\hlcomment{# Another example with with unequal tile sizes}
x.cell.boundary <- \hlfunctioncall{c}(0, 4, 6, 8, 10, 14)
example <- \hlfunctioncall{data.frame}(
x = \hlfunctioncall{rep}(\hlfunctioncall{c}(2, 5, 7, 9, 12), 2),
y = \hlfunctioncall{factor}(\hlfunctioncall{rep}(\hlfunctioncall{c}(1,2), each=5)),
z = \hlfunctioncall{rep}(1:5, each=2),
w = \hlfunctioncall{rep}(\hlfunctioncall{diff}(x.cell.boundary), 2)
)
\hlfunctioncall{qplot}(x, y, fill=z, data=example, geom=\hlstring{"tile"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_tile14}
\begin{kframe}\begin{alltt}
\hlfunctioncall{qplot}(x, y, fill=z, data=example, geom=\hlstring{"tile"}, width=w)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_tile15}
\begin{kframe}\begin{alltt}
\hlfunctioncall{qplot}(x, y, fill=\hlfunctioncall{factor}(z), data=example, geom=\hlstring{"tile"}, width=w)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_tile16}
\begin{kframe}\begin{alltt}
\hlcomment{# You can manually set the colour of the tiles using}
\hlcomment{# scale_manual}
col <- \hlfunctioncall{c}(\hlstring{"darkblue"}, \hlstring{"blue"}, \hlstring{"green"}, \hlstring{"orange"}, \hlstring{"red"})
\hlfunctioncall{qplot}(x, y, fill=col[z], data=example, geom=\hlstring{"tile"}, width=w, group=1) + \hlfunctioncall{scale_fill_identity}(labels=letters[1:5], breaks=col)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_tile17}
\begin{kframe}\begin{alltt}
\hlcomment{## End(No test)}
\end{alltt}
\end{kframe}
\end{knitrout}
\section{geom\_violin}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlcomment{### Name: geom_violin}
\hlcomment{### Title: Violin plot.}
\hlcomment{### Aliases: geom_violin}
\hlcomment{### ** Examples}
\hlcomment{## No test: }
p <- \hlfunctioncall{ggplot}(mtcars, \hlfunctioncall{aes}(\hlfunctioncall{factor}(cyl), mpg))
p + \hlfunctioncall{geom_violin}()
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_violin1}
\begin{kframe}\begin{alltt}
\hlfunctioncall{qplot}(\hlfunctioncall{factor}(cyl), mpg, data = mtcars, geom = \hlstring{"violin"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_violin2}
\begin{kframe}\begin{alltt}
p + \hlfunctioncall{geom_violin}() + \hlfunctioncall{geom_jitter}(height = 0)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_violin3}
\begin{kframe}\begin{alltt}
p + \hlfunctioncall{geom_violin}() + \hlfunctioncall{coord_flip}()
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_violin4}
\begin{kframe}\begin{alltt}
\hlfunctioncall{qplot}(\hlfunctioncall{factor}(cyl), mpg, data = mtcars, geom = \hlstring{"violin"}) +
\hlfunctioncall{coord_flip}()
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_violin5}
\begin{kframe}\begin{alltt}
\hlcomment{# Scale maximum width proportional to sample size:}
p + \hlfunctioncall{geom_violin}(scale = \hlstring{"count"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_violin6}
\begin{kframe}\begin{alltt}
\hlcomment{# Default is to trim violins to the range of the data. To disable:}
p + \hlfunctioncall{geom_violin}(trim = FALSE)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_violin7}
\begin{kframe}\begin{alltt}
\hlcomment{# Use a smaller bandwidth for closer density fit (default is 1).}
p + \hlfunctioncall{geom_violin}(adjust = .5)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_violin8}
\begin{kframe}\begin{alltt}
\hlcomment{# Add aesthetic mappings}
\hlcomment{# Note that violins are automatically dodged when any aesthetic is}
\hlcomment{# a factor}
p + \hlfunctioncall{geom_violin}(\hlfunctioncall{aes}(fill = cyl))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_violin9}
\begin{kframe}\begin{alltt}
p + \hlfunctioncall{geom_violin}(\hlfunctioncall{aes}(fill = \hlfunctioncall{factor}(cyl)))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_violin10}
\begin{kframe}\begin{alltt}
p + \hlfunctioncall{geom_violin}(\hlfunctioncall{aes}(fill = \hlfunctioncall{factor}(vs)))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_violin11}
\begin{kframe}\begin{alltt}
p + \hlfunctioncall{geom_violin}(\hlfunctioncall{aes}(fill = \hlfunctioncall{factor}(am)))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_violin12}
\begin{kframe}\begin{alltt}
\hlcomment{# Set aesthetics to fixed value}
p + \hlfunctioncall{geom_violin}(fill = \hlstring{"grey80"}, colour = \hlstring{"#3366FF"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_violin13}
\begin{kframe}\begin{alltt}
\hlfunctioncall{qplot}(\hlfunctioncall{factor}(cyl), mpg, data = mtcars, geom = \hlstring{"violin"},
colour = \hlfunctioncall{I}(\hlstring{"#3366FF"}))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_violin14}
\begin{kframe}\begin{alltt}
\hlcomment{# Scales vs. coordinate transforms -------}
\hlcomment{# Scale transformations occur before the density statistics are computed.}
\hlcomment{# Coordinate transformations occur afterwards. Observe the effect on the}
\hlcomment{# number of outliers.}
\hlfunctioncall{library}(plyr) \hlcomment{# to access round_any}
m <- \hlfunctioncall{ggplot}(movies, \hlfunctioncall{aes}(y = votes, x = rating,
group = \hlfunctioncall{round_any}(rating, 0.5)))
m + \hlfunctioncall{geom_violin}()
\end{alltt}
{\ttfamily\noindent\textcolor{warningcolor}{\#\# Warning: position\_dodge requires constant width: output may be incorrect}}\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_violin15}
\begin{kframe}\begin{alltt}
m + \hlfunctioncall{geom_violin}() + \hlfunctioncall{scale_y_log10}()
\end{alltt}
{\ttfamily\noindent\textcolor{warningcolor}{\#\# Warning: position\_dodge requires constant width: output may be incorrect}}\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_violin16}
\begin{kframe}\begin{alltt}
m + \hlfunctioncall{geom_violin}() + \hlfunctioncall{coord_trans}(y = \hlstring{"log10"})
\end{alltt}
{\ttfamily\noindent\textcolor{warningcolor}{\#\# Warning: position\_dodge requires constant width: output may be incorrect}}\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_violin17}
\begin{kframe}\begin{alltt}
m + \hlfunctioncall{geom_violin}() + \hlfunctioncall{scale_y_log10}() + \hlfunctioncall{coord_trans}(y = \hlstring{"log10"})
\end{alltt}
{\ttfamily\noindent\textcolor{warningcolor}{\#\# Warning: position\_dodge requires constant width: output may be incorrect}}\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_violin18}
\begin{kframe}\begin{alltt}
\hlcomment{# Violin plots with continuous x:}
\hlcomment{# Use the group aesthetic to group observations in violins}
\hlfunctioncall{qplot}(year, budget, data = movies, geom = \hlstring{"violin"})
\end{alltt}
{\ttfamily\noindent\textcolor{warningcolor}{\#\# Warning: Removed 904 rows containing non-finite values (stat\_ydensity).}}\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_violin19}
\begin{kframe}\begin{alltt}
\hlfunctioncall{qplot}(year, budget, data = movies, geom = \hlstring{"violin"},
group = \hlfunctioncall{round_any}(year, 10, floor))
\end{alltt}
{\ttfamily\noindent\textcolor{warningcolor}{\#\# Warning: Removed 904 rows containing non-finite values (stat\_ydensity).}}
{\ttfamily\noindent\textcolor{warningcolor}{\#\# Warning: position\_dodge requires constant width: output may be incorrect}}\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_violin20}
\begin{kframe}\begin{alltt}
\hlcomment{## End(No test)}
\end{alltt}
\end{kframe}
\end{knitrout}
\section{geom\_vline}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlcomment{### Name: geom_vline}
\hlcomment{### Title: Line, vertical.}
\hlcomment{### Aliases: geom_vline}
\hlcomment{### ** Examples}
\hlcomment{# Fixed lines}
p <- \hlfunctioncall{ggplot}(mtcars, \hlfunctioncall{aes}(x = wt, y = mpg)) + \hlfunctioncall{geom_point}()
p + \hlfunctioncall{geom_vline}(xintercept = 5)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_vline1}
\begin{kframe}\begin{alltt}
p + \hlfunctioncall{geom_vline}(xintercept = 1:5)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_vline2}
\begin{kframe}\begin{alltt}
p + \hlfunctioncall{geom_vline}(xintercept = 1:5, colour=\hlstring{"green"}, linetype = \hlstring{"longdash"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_vline3}
\begin{kframe}\begin{alltt}
p + \hlfunctioncall{geom_vline}(\hlfunctioncall{aes}(xintercept = wt))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_vline4}
\begin{kframe}\begin{alltt}
\hlcomment{# With coordinate transforms}
p + \hlfunctioncall{geom_vline}(\hlfunctioncall{aes}(xintercept = wt)) + \hlfunctioncall{coord_equal}()
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_vline5}
\begin{kframe}\begin{alltt}
p + \hlfunctioncall{geom_vline}(\hlfunctioncall{aes}(xintercept = wt)) + \hlfunctioncall{coord_flip}()
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_vline6}
\begin{kframe}\begin{alltt}
p + \hlfunctioncall{geom_vline}(\hlfunctioncall{aes}(xintercept = wt)) + \hlfunctioncall{coord_polar}()
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_vline7}
\begin{kframe}\begin{alltt}
p2 <- p + \hlfunctioncall{aes}(colour = \hlfunctioncall{factor}(cyl))
p2 + \hlfunctioncall{geom_vline}(xintercept = 15)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_vline8}
\begin{kframe}\begin{alltt}
\hlcomment{# To display different lines in different facets, you need to}
\hlcomment{# create a data frame.}
p <- \hlfunctioncall{qplot}(mpg, wt, data=mtcars, facets = vs ~ am)
vline.data <- \hlfunctioncall{data.frame}(z = \hlfunctioncall{c}(15, 20, 25, 30), vs = \hlfunctioncall{c}(0, 0, 1, 1), am = \hlfunctioncall{c}(0, 1, 0, 1))
p + \hlfunctioncall{geom_vline}(\hlfunctioncall{aes}(xintercept = z), vline.data)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/021-ggplot2-geoms-geom_vline9}
\begin{kframe}\begin{alltt}
\end{alltt}
\end{kframe}
\end{knitrout}
\end{document}
a lovely quiet paragraph
  no code exists
    still a valid knitr document

-- My haiku on an empty document

a lovely quiet paragraph
no code exists
still a valid knitr document
-- My haiku on an empty document

R works, of course.

set.seed(123)
rnorm(5)
## [1] -0.56048 -0.23018  1.55871  0.07051  0.12929

Does knitr work with Python? Use the chunk option engine='python':

x = 'hello, python world!'
print x
print x.split(' ')
## hello, python world!
## ['hello,', 'python', 'world!']

If all the chunks below are python chunks, we can set the engine globally:

Chunk Options

You can use some chunk options like eval, echo and results. For example, eval=FALSE (do not evaluate code):

x = 'hello, python world!'
print x
print x.split(' ')

or echo=FALSE (hide source code):

## hello, python world!
## ['hello,', 'python', 'world!']

or results='hide':

x = 'hello, python world!'
print x
print x.split(' ')

or results='asis':

print '**Write** _something_ in `Markdown` from `Python`!'

Write something in Markdown from Python!

You can also cache the computation:

import time
# pretend this is a time-consuming task...
time.sleep(10)
print 1+1
## 2

Strict Markdown

You can use strict markdown (i.e. indent by 4 spaces) by setting render_markdown(TRUE).

render_markdown(TRUE)

Now see how the output is changed:

x = 'hello, python world!'
print x
print x.split(' ')

## hello, python world!
## ['hello,', 'python', 'world!']
R works, of course.
```{r test-r, engine='R'}
set.seed(123)
rnorm(5)
```
Does **knitr** work with Python? Use the chunk option `engine='python'`:
```{r test-python, engine='python'}
x = 'hello, python world!'
print x
print x.split(' ')
```
If all the chunks below are python chunks, we can set the engine globally:
```{r setup, include=FALSE}
opts_chunk$set(engine = 'python')
```
## Chunk Options
You can use some chunk options like `eval`, `echo` and `results`. For example, `eval=FALSE` (do not evaluate code):
```{r test-eval, eval=FALSE, ref.label='test-python'}
```
or `echo=FALSE` (hide source code):
```{r test-echo, echo=FALSE, ref.label='test-python'}
```
or `results='hide'`:
```{r test-hide, results='hide', ref.label='test-python'}
```
or `results='asis'`:
```{r test-asis, results='asis'}
print '**Write** _something_ in `Markdown` from `Python`!'
```
You can also cache the computation:
```{r test-cache, cache=TRUE}
import time
# pretend this is a time-consuming task...
time.sleep(10)
print 1+1
```
## Strict Markdown
You can use strict markdown (i.e. indent by 4 spaces) by setting `render_markdown(TRUE)`.
```{r strict-markdown, engine='R'}
render_markdown(TRUE)
```
Now see how the output is changed:
```{r test-py-again, ref.label='test-python'}
```

Does Awk work in knitr?

We need to pass a file option to Awk.

# how many non-empty lines?
NF {
  i = i + 1
}
END { print i }
## 598
Does Awk work in **knitr**?
We need to pass a `file` option to Awk.
```{r test-awk, engine='awk', engine.opts=shQuote(system.file('examples', 'knitr-manual.Rnw', package = 'knitr'))}
# how many non-empty lines?
NF {
i = i + 1
}
END { print i }
```

Does Ruby work with knitr?

x = 'hello, ruby world!'
p x.split(' ')
## ["hello,", "ruby", "world!"]
Does Ruby work with **knitr**?
```{r test-ruby, engine='ruby'}
x = 'hello, ruby world!'
p x.split(' ')
```

Does Haskell work with knitr?

Note we have to specify the compiler manually, e.g. engine.path='ghc' (haskell itself may not exist as an executable program).

[x | x <- [1..10], odd x]
## [1,3,5,7,9]
Does Haskell work with **knitr**?
Note we have to specify the compiler manually, e.g. `engine.path='ghc'` (`haskell` itself may not exist as an executable program).
```{r test-haskell, engine='haskell', engine.path='ghc', cache=TRUE}
[x | x <- [1..10], odd x]
```

Run bash scripts

# should exist
Sys.which("bash")
##        bash 
## "/bin/bash"
Sys.which("sh")
##        sh 
## "/bin/sh"

Does bash work?

echo hello world
echo 'a b c' | sed 's/ /\|/g'
# number of lines
awk 'END{print NR;}' 027-engine-bash.Rmd
## hello world
## a|b|c
## 23

How about sh?

# run wc on all engine examples
ls | grep engine | xargs wc
##   108   208  1423 023-engine-python.md
##    65   165  1292 023-engine-python.Rmd
##    17    38   162 024-engine-awk.md
##    11    41   252 024-engine-awk.Rmd
##    13    21   128 025-engine-ruby.md
##     7    17   109 025-engine-ruby.Rmd
##    14    37   235 026-engine-haskell.md
##     8    37   267 026-engine-haskell.Rmd
##    76   204  1457 027-engine-bash.md
##    23    58   352 027-engine-bash.Rmd
##    27    35   222 028-engine-perl.md
##    14    26   172 028-engine-perl.Rmd
##   129   354  2645 029-engine-Rcpp.md
##    97   345  2685 029-engine-Rcpp.Rmd
##    23    56   528 057-engine-dot.md
##    18    62   474 057-engine-dot.Rmd
##    40   183  1371 058-engine-tikz.md
##    35   193  1346 058-engine-tikz.Rmd
##    15    67   425 060-engine-sas.md
##    13    72   537 060-engine-sas.Rmd
##    64   136  1043 080-engine-coffeescript.md
##    29    98   877 080-engine-coffeescript.Rmd
##    45    60   336 090-engine-c.md
##    21    41   256 090-engine-c.Rmd
##   912  2554 18594 total
# Run bash scripts
```{r}
# should exist
Sys.which('bash')
Sys.which('sh')
```
Does `bash` work?
```{r test-bash, engine='bash'}
echo hello world
echo 'a b c' | sed 's/ /\|/g'
# number of lines
awk 'END{print NR;}' 027-engine-bash.Rmd
```
How about `sh`?
```{r test-sh, engine='sh'}
# run wc on all engine examples
ls | grep engine | xargs wc
```

Run perl scripts

# should exist
Sys.which("perl")
##            perl 
## "/usr/bin/perl"

Does perl work?

$test = "jello world";
$test =~ s/j/h/;
print $test
## hello world
# Run perl scripts
```{r}
# should exist
Sys.which('perl')
```
Does `perl` work?
```{r test-perl, engine='perl'}
$test = "jello world";
$test =~ s/j/h/;
print $test
```

Call Rcpp from knitr

When the chunk option engine='Rcpp' is specified, the code chunk will be compiled through Rcpp via sourceCpp():

Test for fibonacci:

#include <Rcpp.h>

// [[Rcpp::export]]
int fibonacci(const int x) {
    if (x == 0 || x == 1) return(x);
    return (fibonacci(x - 1)) + fibonacci(x - 2);
}

Because fibonacci was defined with the Rcpp::export attribute it can now be called as a normal R function:

fibonacci(10L)
## [1] 55
fibonacci(20L)
## [1] 6765

You can define multiple functions (or helper functions that are not exported) within Rcpp code chunks:

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
NumericVector convolveCpp(NumericVector a, NumericVector b) {

    int na = a.size(), nb = b.size();
    int nab = na + nb - 1;
    NumericVector xab(nab);

    for (int i = 0; i < na; i++)
        for (int j = 0; j < nb; j++)
            xab[i + j] += a[i] * b[j];

    return xab;
}

// [[Rcpp::export]]
List lapplyCpp(List input, Function f) {

    List output(input.size());

    std::transform(input.begin(), input.end(), output.begin(), f);
    output.names() = input.names();

    return output;
}

If you want to link to code defined in another package (e.g RcppArmadillo) then you need to provide an Rcpp::depends attribute. For example:

// [[Rcpp::depends(RcppArmadillo)]]

#include <RcppArmadillo.h>

using namespace Rcpp;

// [[Rcpp::export]]
List fastLm(NumericVector yr, NumericMatrix Xr) {

    int n = Xr.nrow(), k = Xr.ncol();

    arma::mat X(Xr.begin(), n, k, false); // reuses memory and avoids extra copy
    arma::colvec y(yr.begin(), yr.size(), false);

    arma::colvec coef = arma::solve(X, y);      // fit model y ~ X
    arma::colvec resid = y - X*coef;            // residuals

    double sig2 = arma::as_scalar( arma::trans(resid)*resid/(n-k) );
                                                // std.error of estimate
    arma::colvec stderrest = arma::sqrt(
                    sig2 * arma::diagvec( arma::inv(arma::trans(X)*X)) );

    return List::create(Named("coefficients") = coef,
                        Named("stderr")       = stderrest
    );
}

A test:

fastLm(rnorm(10), matrix(1:20, ncol = 2))
## $coefficients
##          [,1]
## [1,] -0.01973
## [2,]  0.01966
## 
## $stderr
##         [,1]
## [1,] 0.16059
## [2,] 0.06321

Finally, you can pass additional arguments to sourceCpp() via the chunk option engine.opts. For example, we can specify engine.opts=list(showOutput=TRUE, rebuild=FALSE) to show the output of R CMD SHLIB.

# Call Rcpp from knitr
```{r setup, include=FALSE}
opts_chunk$set(cache = TRUE) # because the compilation takes time, let's cache it
```
When the chunk option `engine='Rcpp'` is specified, the code chunk will be compiled through **Rcpp** via `sourceCpp()`:
Test for `fibonacci`:
```{r fibCpp, engine='Rcpp'}
#include <Rcpp.h>
// [[Rcpp::export]]
int fibonacci(const int x) {
if (x == 0 || x == 1) return(x);
return (fibonacci(x - 1)) + fibonacci(x - 2);
}
```
Because `fibonacci` was defined with the `Rcpp::export` attribute it can now be called as a normal R function:
```{r fibTest, dependson='fibCpp'}
fibonacci(10L)
fibonacci(20L)
```
You can define multiple functions (or helper functions that are not exported) within Rcpp code chunks:
```{r multipleCpp, engine='Rcpp'}
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericVector convolveCpp(NumericVector a, NumericVector b) {
int na = a.size(), nb = b.size();
int nab = na + nb - 1;
NumericVector xab(nab);
for (int i = 0; i < na; i++)
for (int j = 0; j < nb; j++)
xab[i + j] += a[i] * b[j];
return xab;
}
// [[Rcpp::export]]
List lapplyCpp(List input, Function f) {
List output(input.size());
std::transform(input.begin(), input.end(), output.begin(), f);
output.names() = input.names();
return output;
}
```
If you want to link to code defined in another package (e.g **RcppArmadillo**) then you need to provide an `Rcpp::depends` attribute. For example:
```{r lmCpp, engine='Rcpp'}
// [[Rcpp::depends(RcppArmadillo)]]
#include <RcppArmadillo.h>
using namespace Rcpp;
// [[Rcpp::export]]
List fastLm(NumericVector yr, NumericMatrix Xr) {
int n = Xr.nrow(), k = Xr.ncol();
arma::mat X(Xr.begin(), n, k, false); // reuses memory and avoids extra copy
arma::colvec y(yr.begin(), yr.size(), false);
arma::colvec coef = arma::solve(X, y); // fit model y ~ X
arma::colvec resid = y - X*coef; // residuals
double sig2 = arma::as_scalar( arma::trans(resid)*resid/(n-k) );
// std.error of estimate
arma::colvec stderrest = arma::sqrt(
sig2 * arma::diagvec( arma::inv(arma::trans(X)*X)) );
return List::create(Named("coefficients") = coef,
Named("stderr") = stderrest
);
}
```
A test:
```{r lmTest, dependson='lmCpp'}
fastLm(rnorm(10), matrix(1:20, ncol = 2))
```
Finally, you can pass additional arguments to `sourceCpp()` via the chunk option `engine.opts`. For example, we can specify `engine.opts=list(showOutput=TRUE, rebuild=FALSE)` to show the output of `R CMD SHLIB`.
\documentclass{article}
\usepackage{lscape}
\begin{document}
See if the landscape environment works.
hello world
\newpage
\begin{landscape}
\tiny
<<results='asis', cache=TRUE>>=
library(xtable)
print(xtable(head(iris)))
@
\end{landscape}
\newpage
hello again
<<results='asis'>>=
library(Hmisc)
latex(head(iris), file='', size="tiny", landscape=TRUE)
@
\end{document}
\documentclass{article}\usepackage[]{graphicx}\usepackage[]{color}
%% maxwidth is the original width if it is less than linewidth
%% otherwise use linewidth (to make sure the graphics do not exceed the margin)
\makeatletter
\def\maxwidth{ %
\ifdim\Gin@nat@width>\linewidth
\linewidth
\else
\Gin@nat@width
\fi
}
\makeatother
\definecolor{fgcolor}{rgb}{0.2, 0.2, 0.2}
\newcommand{\hlnumber}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlfunctioncall}[1]{\textcolor[rgb]{0.501960784313725,0,0.329411764705882}{\textbf{#1}}}%
\newcommand{\hlstring}[1]{\textcolor[rgb]{0.6,0.6,1}{#1}}%
\newcommand{\hlkeyword}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlargument}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlcomment}[1]{\textcolor[rgb]{0.180392156862745,0.6,0.341176470588235}{#1}}%
\newcommand{\hlroxygencomment}[1]{\textcolor[rgb]{0.43921568627451,0.47843137254902,0.701960784313725}{#1}}%
\newcommand{\hlformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hleqformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlassignement}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlpackage}[1]{\textcolor[rgb]{0.588235294117647,0.709803921568627,0.145098039215686}{#1}}%
\newcommand{\hlslot}[1]{\textit{#1}}%
\newcommand{\hlsymbol}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlprompt}[1]{\textcolor[rgb]{0.2,0.2,0.2}{#1}}%
\usepackage{framed}
\makeatletter
\newenvironment{kframe}{%
\def\at@end@of@kframe{}%
\ifinner\ifhmode%
\def\at@end@of@kframe{\end{minipage}}%
\begin{minipage}{\columnwidth}%
\fi\fi%
\def\FrameCommand##1{\hskip\@totalleftmargin \hskip-\fboxsep
\colorbox{shadecolor}{##1}\hskip-\fboxsep
% There is no \\@totalrightmargin, so:
\hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth}%
\MakeFramed {\advance\hsize-\width
\@totalleftmargin\z@ \linewidth\hsize
\@setminipage}}%
{\par\unskip\endMakeFramed%
\at@end@of@kframe}
\makeatother
\definecolor{shadecolor}{rgb}{.97, .97, .97}
\definecolor{messagecolor}{rgb}{0, 0, 0}
\definecolor{warningcolor}{rgb}{1, 0, 1}
\definecolor{errorcolor}{rgb}{1, 0, 0}
\newenvironment{knitrout}{}{} % an empty environment to be redefined in TeX
\usepackage{alltt}
\usepackage{lscape}
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
\begin{document}
See if the landscape environment works.
hello world
\newpage
\begin{landscape}
\tiny
\begin{kframe}
\begin{alltt}
\hlfunctioncall{library}(xtable)
\hlfunctioncall{print}(\hlfunctioncall{xtable}(\hlfunctioncall{head}(iris)))
\end{alltt}
\end{kframe}
% latex table generated in R 2.15.1 by xtable 1.7-0 package
% Tue Aug 21 23:12:18 2012
\begin{table}[ht]
\begin{center}
\begin{tabular}{rrrrrl}
\hline
& Sepal.Length & Sepal.Width & Petal.Length & Petal.Width & Species \\
\hline
1 & 5.10 & 3.50 & 1.40 & 0.20 & setosa \\
2 & 4.90 & 3.00 & 1.40 & 0.20 & setosa \\
3 & 4.70 & 3.20 & 1.30 & 0.20 & setosa \\
4 & 4.60 & 3.10 & 1.50 & 0.20 & setosa \\
5 & 5.00 & 3.60 & 1.40 & 0.20 & setosa \\
6 & 5.40 & 3.90 & 1.70 & 0.40 & setosa \\
\hline
\end{tabular}
\end{center}
\end{table}
\end{landscape}
\newpage
hello again
\begin{kframe}
\begin{alltt}
\hlfunctioncall{library}(Hmisc)
\end{alltt}
{\ttfamily\noindent\itshape\color{messagecolor}{\#\# Loading required package: methods\\\#\# Loading required package: survival\\\#\# Loading required package: splines\\\#\# Hmisc library by Frank E Harrell Jr\\\#\# \\\#\# Type library(help='Hmisc'), ?Overview, or ?Hmisc.Overview')\\\#\# to see overall documentation.\\\#\# \\\#\# NOTE:Hmisc no longer redefines [.factor to drop unused levels when\\\#\# subsetting.\ \ To get the old behavior of Hmisc type dropUnusedLevels().\\\#\# \\\#\# \\\#\# Attaching package: 'Hmisc'\\\#\# \\\#\# The following object is masked from 'package:survival':\\\#\# \\\#\#\ \ \ \ untangle.specials\\\#\# \\\#\# The following object is masked from 'package:base':\\\#\# \\\#\#\ \ \ \ format.pval, round.POSIXt, trunc.POSIXt, units}}\begin{alltt}
\hlfunctioncall{latex}(\hlfunctioncall{head}(iris), file = \hlstring{""}, size = \hlstring{"tiny"}, landscape = TRUE)
\end{alltt}
\end{kframe}% latex.default(head(iris), file = "", size = "tiny", landscape = TRUE)
%
\begin{landscape}\begin{table}[!tbp]
\tiny
\begin{center}
\begin{tabular}{lrrrrl}
\hline\hline
\multicolumn{1}{l}{head}&\multicolumn{1}{c}{Sepal.Length}&\multicolumn{1}{c}{Sepal.Width}&\multicolumn{1}{c}{Petal.Length}&\multicolumn{1}{c}{Petal.Width}&\multicolumn{1}{c}{Species}\tabularnewline
\hline
1&$5.1$&$3.5$&$1.4$&$0.2$&setosa\tabularnewline
2&$4.9$&$3.0$&$1.4$&$0.2$&setosa\tabularnewline
3&$4.7$&$3.2$&$1.3$&$0.2$&setosa\tabularnewline
4&$4.6$&$3.1$&$1.5$&$0.2$&setosa\tabularnewline
5&$5.0$&$3.6$&$1.4$&$0.2$&setosa\tabularnewline
6&$5.4$&$3.9$&$1.7$&$0.4$&setosa\tabularnewline
\hline
\end{tabular}
\end{center}
\end{table}
\end{landscape}
\end{document}
\documentclass{article}
\begin{document}
Sometimes we do not want the text following a code chunk to be indented as a paragraph. We can use the \texttt{document} hook to add \texttt{\textbackslash{}noindent} after each chunk. For example:
<<setup>>=
knit_hooks$set(document = function(x) {
gsub('(\\\\end\\{knitrout\\}[\n]+)', '\\1\\\\noindent ', paste(x, collapse = '\n'))
})
@
See if it works.
<<>>=
# hello world
1+1
@
I'm not indented. That is great.
A new paragraph is indented again.
\end{document}
\documentclass{article}\usepackage[]{graphicx}\usepackage[]{color}
%% maxwidth is the original width if it is less than linewidth
%% otherwise use linewidth (to make sure the graphics do not exceed the margin)
\makeatletter
\def\maxwidth{ %
\ifdim\Gin@nat@width>\linewidth
\linewidth
\else
\Gin@nat@width
\fi
}
\makeatother
\definecolor{fgcolor}{rgb}{0.2, 0.2, 0.2}
\newcommand{\hlnumber}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlfunctioncall}[1]{\textcolor[rgb]{0.501960784313725,0,0.329411764705882}{\textbf{#1}}}%
\newcommand{\hlstring}[1]{\textcolor[rgb]{0.6,0.6,1}{#1}}%
\newcommand{\hlkeyword}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlargument}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlcomment}[1]{\textcolor[rgb]{0.180392156862745,0.6,0.341176470588235}{#1}}%
\newcommand{\hlroxygencomment}[1]{\textcolor[rgb]{0.43921568627451,0.47843137254902,0.701960784313725}{#1}}%
\newcommand{\hlformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hleqformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlassignement}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlpackage}[1]{\textcolor[rgb]{0.588235294117647,0.709803921568627,0.145098039215686}{#1}}%
\newcommand{\hlslot}[1]{\textit{#1}}%
\newcommand{\hlsymbol}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlprompt}[1]{\textcolor[rgb]{0.2,0.2,0.2}{#1}}%
\usepackage{framed}
\makeatletter
\newenvironment{kframe}{%
\def\at@end@of@kframe{}%
\ifinner\ifhmode%
\def\at@end@of@kframe{\end{minipage}}%
\begin{minipage}{\columnwidth}%
\fi\fi%
\def\FrameCommand##1{\hskip\@totalleftmargin \hskip-\fboxsep
\colorbox{shadecolor}{##1}\hskip-\fboxsep
% There is no \\@totalrightmargin, so:
\hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth}%
\MakeFramed {\advance\hsize-\width
\@totalleftmargin\z@ \linewidth\hsize
\@setminipage}}%
{\par\unskip\endMakeFramed%
\at@end@of@kframe}
\makeatother
\definecolor{shadecolor}{rgb}{.97, .97, .97}
\definecolor{messagecolor}{rgb}{0, 0, 0}
\definecolor{warningcolor}{rgb}{1, 0, 1}
\definecolor{errorcolor}{rgb}{1, 0, 0}
\newenvironment{knitrout}{}{} % an empty environment to be redefined in TeX
\usepackage{alltt}
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
\begin{document}
Sometimes we do not want the text following a code chunk to be indented as a paragraph. We can use the \texttt{document} hook to add \texttt{\textbackslash{}noindent} after each chunk. For example:
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
knit_hooks$\hlfunctioncall{set}(document = \hlfunctioncall{function}(x) \{
\hlfunctioncall{gsub}(\hlstring{"(\textbackslash{}\textbackslash{}\textbackslash{}\textbackslash{}end\textbackslash{}\textbackslash{}\{knitrout\textbackslash{}\textbackslash{}\}[\textbackslash{}n]+)"}, \hlstring{"\textbackslash{}\textbackslash{}1\textbackslash{}\textbackslash{}\textbackslash{}\textbackslash{}noindent "},
\hlfunctioncall{paste}(x, collapse = \hlstring{"\textbackslash{}n"}))
\})
\end{alltt}
\end{kframe}
\end{knitrout}
\noindent See if it works.
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlcomment{# hello world}
1 + 1
\end{alltt}
\begin{verbatim}
## [1] 2
\end{verbatim}
\end{kframe}
\end{knitrout}
\noindent I'm not indented. That is great.
A new paragraph is indented again.
\end{document}
\documentclass{article}
\begin{document}
persp() plots should appear here:
<<persp-plot, cache=TRUE>>=
x <- seq(-10, 10, length= 30)
y <- x
f <- function(x,y) { r <- sqrt(x^2+y^2); 10 * sin(r)/r }
z <- outer(x, y, f)
z[is.na(z)] <- 1
persp(x, y, z, theta = 30, phi = 30)
@
\end{document}
\documentclass{article}\usepackage[]{graphicx}\usepackage[]{color}
%% maxwidth is the original width if it is less than linewidth
%% otherwise use linewidth (to make sure the graphics do not exceed the margin)
\makeatletter
\def\maxwidth{ %
\ifdim\Gin@nat@width>\linewidth
\linewidth
\else
\Gin@nat@width
\fi
}
\makeatother
\definecolor{fgcolor}{rgb}{0.2, 0.2, 0.2}
\newcommand{\hlnumber}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlfunctioncall}[1]{\textcolor[rgb]{0.501960784313725,0,0.329411764705882}{\textbf{#1}}}%
\newcommand{\hlstring}[1]{\textcolor[rgb]{0.6,0.6,1}{#1}}%
\newcommand{\hlkeyword}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlargument}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlcomment}[1]{\textcolor[rgb]{0.180392156862745,0.6,0.341176470588235}{#1}}%
\newcommand{\hlroxygencomment}[1]{\textcolor[rgb]{0.43921568627451,0.47843137254902,0.701960784313725}{#1}}%
\newcommand{\hlformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hleqformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlassignement}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlpackage}[1]{\textcolor[rgb]{0.588235294117647,0.709803921568627,0.145098039215686}{#1}}%
\newcommand{\hlslot}[1]{\textit{#1}}%
\newcommand{\hlsymbol}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlprompt}[1]{\textcolor[rgb]{0.2,0.2,0.2}{#1}}%
\usepackage{framed}
\makeatletter
\newenvironment{kframe}{%
\def\at@end@of@kframe{}%
\ifinner\ifhmode%
\def\at@end@of@kframe{\end{minipage}}%
\begin{minipage}{\columnwidth}%
\fi\fi%
\def\FrameCommand##1{\hskip\@totalleftmargin \hskip-\fboxsep
\colorbox{shadecolor}{##1}\hskip-\fboxsep
% There is no \\@totalrightmargin, so:
\hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth}%
\MakeFramed {\advance\hsize-\width
\@totalleftmargin\z@ \linewidth\hsize
\@setminipage}}%
{\par\unskip\endMakeFramed%
\at@end@of@kframe}
\makeatother
\definecolor{shadecolor}{rgb}{.97, .97, .97}
\definecolor{messagecolor}{rgb}{0, 0, 0}
\definecolor{warningcolor}{rgb}{1, 0, 1}
\definecolor{errorcolor}{rgb}{1, 0, 0}
\newenvironment{knitrout}{}{} % an empty environment to be redefined in TeX
\usepackage{alltt}
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
\begin{document}
persp() plots should appear here:
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
x <- \hlfunctioncall{seq}(-10, 10, length = 30)
y <- x
f <- \hlfunctioncall{function}(x, y) \{
r <- \hlfunctioncall{sqrt}(x^2 + y^2)
10 * \hlfunctioncall{sin}(r)/r
\}
z <- \hlfunctioncall{outer}(x, y, f)
z[\hlfunctioncall{is.na}(z)] <- 1
\hlfunctioncall{persp}(x, y, z, theta = 30, phi = 30)
\end{alltt}
\end{kframe}\includegraphics[width=\maxwidth]{figure/032-persp-persp-plot}
\end{knitrout}
\end{document}
\documentclass{article}
\begin{document}
We want the file extension when including a figure into LaTeX.
<<setup>>=
knit_hooks$set(plot = function(x, options) {
x = paste(x, collapse = '.') # x is file.ext now instead of c(file, ext)
paste0('\\end{kframe}', hook_plot_tex(x, options), '\\begin{kframe}')
})
@
You should see \textbackslash{}includegraphics\{test.pdf\} instead of \textbackslash{}includegraphics\{test\}.
<<test-a>>=
# pdf figure
plot(1)
@
<<test-b, dev='png'>>=
# png figure
plot(2)
@
\end{document}
\documentclass{article}\usepackage[]{graphicx}\usepackage[]{color}
%% maxwidth is the original width if it is less than linewidth
%% otherwise use linewidth (to make sure the graphics do not exceed the margin)
\makeatletter
\def\maxwidth{ %
\ifdim\Gin@nat@width>\linewidth
\linewidth
\else
\Gin@nat@width
\fi
}
\makeatother
\definecolor{fgcolor}{rgb}{0.2, 0.2, 0.2}
\newcommand{\hlnumber}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlfunctioncall}[1]{\textcolor[rgb]{0.501960784313725,0,0.329411764705882}{\textbf{#1}}}%
\newcommand{\hlstring}[1]{\textcolor[rgb]{0.6,0.6,1}{#1}}%
\newcommand{\hlkeyword}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlargument}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlcomment}[1]{\textcolor[rgb]{0.180392156862745,0.6,0.341176470588235}{#1}}%
\newcommand{\hlroxygencomment}[1]{\textcolor[rgb]{0.43921568627451,0.47843137254902,0.701960784313725}{#1}}%
\newcommand{\hlformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hleqformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlassignement}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlpackage}[1]{\textcolor[rgb]{0.588235294117647,0.709803921568627,0.145098039215686}{#1}}%
\newcommand{\hlslot}[1]{\textit{#1}}%
\newcommand{\hlsymbol}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlprompt}[1]{\textcolor[rgb]{0.2,0.2,0.2}{#1}}%
\usepackage{framed}
\makeatletter
\newenvironment{kframe}{%
\def\at@end@of@kframe{}%
\ifinner\ifhmode%
\def\at@end@of@kframe{\end{minipage}}%
\begin{minipage}{\columnwidth}%
\fi\fi%
\def\FrameCommand##1{\hskip\@totalleftmargin \hskip-\fboxsep
\colorbox{shadecolor}{##1}\hskip-\fboxsep
% There is no \\@totalrightmargin, so:
\hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth}%
\MakeFramed {\advance\hsize-\width
\@totalleftmargin\z@ \linewidth\hsize
\@setminipage}}%
{\par\unskip\endMakeFramed%
\at@end@of@kframe}
\makeatother
\definecolor{shadecolor}{rgb}{.97, .97, .97}
\definecolor{messagecolor}{rgb}{0, 0, 0}
\definecolor{warningcolor}{rgb}{1, 0, 1}
\definecolor{errorcolor}{rgb}{1, 0, 0}
\newenvironment{knitrout}{}{} % an empty environment to be redefined in TeX
\usepackage{alltt}
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
\begin{document}
We want the file extension when including a figure into LaTeX.
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
knit_hooks$\hlfunctioncall{set}(plot = \hlfunctioncall{function}(x, options) \{
x = \hlfunctioncall{paste}(x, collapse = \hlstring{"."}) # x is file.ext now instead of \hlfunctioncall{c}(file, ext)
\hlfunctioncall{paste0}(\hlstring{"\textbackslash{}\textbackslash{}end\{kframe\}"}, \hlfunctioncall{hook_plot_tex}(x, options), \hlstring{"\textbackslash{}\textbackslash{}begin\{kframe\}"})
\})
\end{alltt}
\end{kframe}
\end{knitrout}
You should see \textbackslash{}includegraphics\{test.pdf\} instead of \textbackslash{}includegraphics\{test\}.
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlcomment{# pdf figure}
\hlfunctioncall{plot}(1)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/033-file-extension-test-a.pdf}
\end{knitrout}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlcomment{# png figure}
\hlfunctioncall{plot}(2)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/033-file-extension-test-b.png}
\end{knitrout}
\end{document}
<!DOCTYPE html>
<html>
<head>
<style type="text/css">.knitr.inline {
background-color: #f7f7f7;
border:solid 1px #B0B0B0;
}
.error {
font-weight: bold;
color: #FF0000;
},
.warning {
font-weight: bold;
}
.message {
font-style: italic;
}
.source, .output, .warning, .error, .message {
padding: 0em 1em;
border:solid 1px #F7F7F7;
}
.source {
background-color: #f7f7f7;
}
.rimage.left {
text-align: left;
}
.rimage.right {
text-align: right;
}
.rimage.center {
text-align: center;
}
.source {
color: #333333;
}
.background {
color: #F7F7F7;
}
.number {
color: #000000;
}
.functioncall {
color: #800054;
font-weight: bolder;
}
.string {
color: #9999FF;
}
.keyword {
font-weight: bolder;
color: black;
}
.argument {
color: #B04005;
}
.comment {
color: #2E9957;
}
.roxygencomment {
color: #707AB3;
}
.formalargs {
color: #B04005;
}
.eqformalargs {
color: #B04005;
}
.assignement {
font-weight: bolder;
color: #000000;
}
.package {
color: #96B525;
}
.slot {
font-style: italic;
}
.symbol {
color: #000000;
}
.prompt {
color: #333333;
}
</style>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>你好,中文</title>
</head>
<body>
<p>肿么就不能写中文呢?</p>
<div class="chunk" id="unnamed-chunk-1"><div class="rcode"><div class="source"><pre class="knitr r">x = 1 + 1
<span class="functioncall">pnorm</span>(x)
</pre></div>
<div class="output"><pre class="knitr r">## [1] 0.9772
</pre></div>
<div class="source"><pre class="knitr r"><span class="functioncall">plot</span>(mtcars[, 1:2])
</pre></div>
</div><div class="rimage default"><img src="http://animation.r-forge.r-project.org/knitr-ex/figure/034-chinese-unnamed-chunk-1.png" title="plot of chunk unnamed-chunk-1" alt="plot of chunk unnamed-chunk-1" class="plot" /></div></div>
<p>介不是好好的吗?</p>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>你好,中文</title>
</head>
<body>
<p>肿么就不能写中文呢?</p>
<!--begin.rcode
x=1+1
pnorm(x)
plot(mtcars[, 1:2])
end.rcode-->
<p>介不是好好的吗?</p>
</body>
</html>

This demos shows you how to optimize PNG images with optipng.

opts_chunk$set(cache = TRUE)
knit_hooks$set(optipng = hook_optipng)

Now we set the chunk option optipng to a non-NULL value, e.g. '', to activate the hook.

library(ggplot2)
set.seed(123)
qplot(rnorm(1000), rnorm(1000))

plot of chunk use-optipng

Same plot, not optimized:

library(ggplot2)
set.seed(123)
qplot(rnorm(1000), rnorm(1000))

plot of chunk no-optipng

Same plot, most heavily optimized (pass -o7 to optipng):

library(ggplot2)
set.seed(123)
qplot(rnorm(1000), rnorm(1000))

plot of chunk optipng-o7

This demos shows you how to optimize PNG images with `optipng`.
```{r setup}
opts_chunk$set(cache=TRUE)
knit_hooks$set(optipng = hook_optipng)
```
Now we set the chunk option `optipng` to a non-`NULL` value, e.g. `''`, to activate the hook.
```{r use-optipng, optipng=''}
library(ggplot2)
set.seed(123)
qplot(rnorm(1e3), rnorm(1e3))
```
Same plot, not optimized:
```{r no-optipng, ref.label='use-optipng'}
```
Same plot, most heavily optimized (pass `-o7` to `optipng`):
```{r optipng-o7, ref.label='use-optipng', optipng='-o7'}
```
\documentclass{article}
\newif\ifmyboolean
\begin{document}
<<setup>>=
myboolean='true' # or set it to 'false'
@
% assign true or false to myboolean
\myboolean\Sexpr{myboolean}
\ifmyboolean
hello, foo!
\else
hey, bar!
\fi
\end{document}
\documentclass{article}\usepackage[]{graphicx}\usepackage[]{color}
%% maxwidth is the original width if it is less than linewidth
%% otherwise use linewidth (to make sure the graphics do not exceed the margin)
\makeatletter
\def\maxwidth{ %
\ifdim\Gin@nat@width>\linewidth
\linewidth
\else
\Gin@nat@width
\fi
}
\makeatother
\definecolor{fgcolor}{rgb}{0.2, 0.2, 0.2}
\newcommand{\hlnumber}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlfunctioncall}[1]{\textcolor[rgb]{0.501960784313725,0,0.329411764705882}{\textbf{#1}}}%
\newcommand{\hlstring}[1]{\textcolor[rgb]{0.6,0.6,1}{#1}}%
\newcommand{\hlkeyword}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlargument}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlcomment}[1]{\textcolor[rgb]{0.180392156862745,0.6,0.341176470588235}{#1}}%
\newcommand{\hlroxygencomment}[1]{\textcolor[rgb]{0.43921568627451,0.47843137254902,0.701960784313725}{#1}}%
\newcommand{\hlformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hleqformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlassignement}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlpackage}[1]{\textcolor[rgb]{0.588235294117647,0.709803921568627,0.145098039215686}{#1}}%
\newcommand{\hlslot}[1]{\textit{#1}}%
\newcommand{\hlsymbol}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlprompt}[1]{\textcolor[rgb]{0.2,0.2,0.2}{#1}}%
\usepackage{framed}
\makeatletter
\newenvironment{kframe}{%
\def\at@end@of@kframe{}%
\ifinner\ifhmode%
\def\at@end@of@kframe{\end{minipage}}%
\begin{minipage}{\columnwidth}%
\fi\fi%
\def\FrameCommand##1{\hskip\@totalleftmargin \hskip-\fboxsep
\colorbox{shadecolor}{##1}\hskip-\fboxsep
% There is no \\@totalrightmargin, so:
\hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth}%
\MakeFramed {\advance\hsize-\width
\@totalleftmargin\z@ \linewidth\hsize
\@setminipage}}%
{\par\unskip\endMakeFramed%
\at@end@of@kframe}
\makeatother
\definecolor{shadecolor}{rgb}{.97, .97, .97}
\definecolor{messagecolor}{rgb}{0, 0, 0}
\definecolor{warningcolor}{rgb}{1, 0, 1}
\definecolor{errorcolor}{rgb}{1, 0, 0}
\newenvironment{knitrout}{}{} % an empty environment to be redefined in TeX
\usepackage{alltt}
\newif\ifmyboolean
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
\begin{document}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
myboolean = \hlstring{"true"} # or set it to \hlstring{'false'}
\end{alltt}
\end{kframe}
\end{knitrout}
% assign true or false to myboolean
\mybooleantrue
\ifmyboolean
hello, foo!
\else
hey, bar!
\fi
\end{document}
\documentclass{article}
<<setup, include=FALSE>>=
options(width=60)
# an old solution by @r2d3 was at https://github.com/yihui/knitr/issues/210
# but since knitr 0.9, we can do it through the chunk option tidy.opts
@
\begin{document}
the value of $\pi$ is \Sexpr{pi}, and the function to read a table is \Sexpr{'read.table()'}.
<<test2>>=
rnorm(10)
@
<<test, tidy.opts=list(width.cutoff=30)>>=
getOption('width')
x=1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1
@
% use default global width
<<another-test>>=
getOption('width')
x=1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1
@
\end{document}
\documentclass{article}\usepackage[]{graphicx}\usepackage[]{color}
%% maxwidth is the original width if it is less than linewidth
%% otherwise use linewidth (to make sure the graphics do not exceed the margin)
\makeatletter
\def\maxwidth{ %
\ifdim\Gin@nat@width>\linewidth
\linewidth
\else
\Gin@nat@width
\fi
}
\makeatother
\definecolor{fgcolor}{rgb}{0.2, 0.2, 0.2}
\newcommand{\hlnumber}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlfunctioncall}[1]{\textcolor[rgb]{0.501960784313725,0,0.329411764705882}{\textbf{#1}}}%
\newcommand{\hlstring}[1]{\textcolor[rgb]{0.6,0.6,1}{#1}}%
\newcommand{\hlkeyword}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlargument}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlcomment}[1]{\textcolor[rgb]{0.180392156862745,0.6,0.341176470588235}{#1}}%
\newcommand{\hlroxygencomment}[1]{\textcolor[rgb]{0.43921568627451,0.47843137254902,0.701960784313725}{#1}}%
\newcommand{\hlformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hleqformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlassignement}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlpackage}[1]{\textcolor[rgb]{0.588235294117647,0.709803921568627,0.145098039215686}{#1}}%
\newcommand{\hlslot}[1]{\textit{#1}}%
\newcommand{\hlsymbol}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlprompt}[1]{\textcolor[rgb]{0.2,0.2,0.2}{#1}}%
\usepackage{framed}
\makeatletter
\newenvironment{kframe}{%
\def\at@end@of@kframe{}%
\ifinner\ifhmode%
\def\at@end@of@kframe{\end{minipage}}%
\begin{minipage}{\columnwidth}%
\fi\fi%
\def\FrameCommand##1{\hskip\@totalleftmargin \hskip-\fboxsep
\colorbox{shadecolor}{##1}\hskip-\fboxsep
% There is no \\@totalrightmargin, so:
\hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth}%
\MakeFramed {\advance\hsize-\width
\@totalleftmargin\z@ \linewidth\hsize
\@setminipage}}%
{\par\unskip\endMakeFramed%
\at@end@of@kframe}
\makeatother
\definecolor{shadecolor}{rgb}{.97, .97, .97}
\definecolor{messagecolor}{rgb}{0, 0, 0}
\definecolor{warningcolor}{rgb}{1, 0, 1}
\definecolor{errorcolor}{rgb}{1, 0, 0}
\newenvironment{knitrout}{}{} % an empty environment to be redefined in TeX
\usepackage{alltt}
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
\begin{document}
the value of $\pi$ is 3.1416, and the function to read a table is read.table().
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlfunctioncall{rnorm}(10)
\end{alltt}
\begin{verbatim}
## [1] -0.56048 -0.23018 1.55871 0.07051 0.12929 1.71506
## [7] 0.46092 -1.26506 -0.68685 -0.44566
\end{verbatim}
\end{kframe}
\end{knitrout}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlfunctioncall{getOption}(\hlstring{"width"})
\end{alltt}
\begin{verbatim}
## [1] 60
\end{verbatim}
\begin{alltt}
x = 1 + 1 + 1 + 1 + 1 + 1 + 1 +
1 + 1 + 1 + 1 + 1 + 1 + 1 +
1 + 1 + 1 + 1 + 1 + 1 + 1 +
1 + 1 + 1 + 1 + 1 + 1 + 1 +
1 + 1 + 1 + 1 + 1 + 1 + 1 +
1 + 1 + 1 + 1 + 1 + 1 + 1 +
1 + 1 + 1 + 1 + 1 + 1 + 1 +
1
\end{alltt}
\end{kframe}
\end{knitrout}
% use default global width
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlfunctioncall{getOption}(\hlstring{"width"})
\end{alltt}
\begin{verbatim}
## [1] 60
\end{verbatim}
\begin{alltt}
x = 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 +
1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 +
1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 +
1 + 1 + 1 + 1 + 1
\end{alltt}
\end{kframe}
\end{knitrout}
\end{document}

This demo shows you how to merge the source and output blocks in markdown output. Note knitr puts R source and output in separate blocks by default.

# first ``` are the end of previous source block; second ``` are the
# beginning of next output block
knit_hooks$set(chunk = function(x, options) {
    gsub("```\n+```", "", x)
})

See if it works:

a = 1
a

## [1] 1

Source and output lived together happily ever in knitr.

This demo shows you how to merge the source and output blocks in markdown output. Note **knitr** puts R source and output in separate blocks by default.
```{r setup}
# first ``` are the end of previous source block; second ``` are the beginning
# of next output block
knit_hooks$set(chunk = function(x, options) {
gsub('```\n+```', '', x)
})
```
See if it works:
```{r test}
a = 1
a
```
Source and output lived together happily ever in **knitr**.
\documentclass{article}
\begin{document}
We can draw a table with the gridExtra package, and one problem is to
pre-determine the size of the table plot to remove the extra white
margin. Below is an example that shows you how to do it (courtesy of
baptiste auguie).
<<setup>>=
library(gridExtra)
g = tableGrob(head(iris, 4))
<<draw-table, dev='png', dpi=150, fig.width=convertWidth(grobWidth(g), "in", value=TRUE), fig.height=convertHeight(grobHeight(g), "in", value=TRUE)>>=
grid.draw(g)
@
\end{document}
\documentclass{article}\usepackage[]{graphicx}\usepackage[]{color}
%% maxwidth is the original width if it is less than linewidth
%% otherwise use linewidth (to make sure the graphics do not exceed the margin)
\makeatletter
\def\maxwidth{ %
\ifdim\Gin@nat@width>\linewidth
\linewidth
\else
\Gin@nat@width
\fi
}
\makeatother
\definecolor{fgcolor}{rgb}{0.2, 0.2, 0.2}
\newcommand{\hlnumber}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlfunctioncall}[1]{\textcolor[rgb]{0.501960784313725,0,0.329411764705882}{\textbf{#1}}}%
\newcommand{\hlstring}[1]{\textcolor[rgb]{0.6,0.6,1}{#1}}%
\newcommand{\hlkeyword}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlargument}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlcomment}[1]{\textcolor[rgb]{0.180392156862745,0.6,0.341176470588235}{#1}}%
\newcommand{\hlroxygencomment}[1]{\textcolor[rgb]{0.43921568627451,0.47843137254902,0.701960784313725}{#1}}%
\newcommand{\hlformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hleqformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlassignement}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlpackage}[1]{\textcolor[rgb]{0.588235294117647,0.709803921568627,0.145098039215686}{#1}}%
\newcommand{\hlslot}[1]{\textit{#1}}%
\newcommand{\hlsymbol}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlprompt}[1]{\textcolor[rgb]{0.2,0.2,0.2}{#1}}%
\usepackage{framed}
\makeatletter
\newenvironment{kframe}{%
\def\at@end@of@kframe{}%
\ifinner\ifhmode%
\def\at@end@of@kframe{\end{minipage}}%
\begin{minipage}{\columnwidth}%
\fi\fi%
\def\FrameCommand##1{\hskip\@totalleftmargin \hskip-\fboxsep
\colorbox{shadecolor}{##1}\hskip-\fboxsep
% There is no \\@totalrightmargin, so:
\hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth}%
\MakeFramed {\advance\hsize-\width
\@totalleftmargin\z@ \linewidth\hsize
\@setminipage}}%
{\par\unskip\endMakeFramed%
\at@end@of@kframe}
\makeatother
\definecolor{shadecolor}{rgb}{.97, .97, .97}
\definecolor{messagecolor}{rgb}{0, 0, 0}
\definecolor{warningcolor}{rgb}{1, 0, 1}
\definecolor{errorcolor}{rgb}{1, 0, 0}
\newenvironment{knitrout}{}{} % an empty environment to be redefined in TeX
\usepackage{alltt}
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
\begin{document}
We can draw a table with the gridExtra package, and one problem is to
pre-determine the size of the table plot to remove the extra white
margin. Below is an example that shows you how to do it (courtesy of
baptiste auguie).
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlfunctioncall{library}(gridExtra)
\end{alltt}
{\ttfamily\noindent\itshape\color{messagecolor}{\#\# Loading required package: grid}}\begin{alltt}
g = \hlfunctioncall{tableGrob}(\hlfunctioncall{head}(iris, 4))
\end{alltt}
\end{kframe}
\end{knitrout}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlfunctioncall{grid.draw}(g)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/040-grid-table-draw-table}
\end{knitrout}
\end{document}
```{r header-<% cur.cyl %>, results='asis', echo=FALSE}
cat("###", <% cur.cyl %>)
```
```{r mpg-histogram-<% cur.cyl %>}
hist(mtcars$mpg[mtcars$cyl == <% cur.cyl %>], main = paste(<% cur.cyl %>, "cylinders"))
```
```{r weight-histogam-<% cur.cyl %>}
hist(mtcars$wt[mtcars$cyl == <% cur.cyl %>], main = paste(<% cur.cyl %>, "cylinders"))
```

My report

data(mtcars)

This example shows how to generate chunk labels dynamically with the brew syntax. It was motivated by the SO question: http://stackoverflow.com/q/12095113/559676

Generate report for each level of cylinder variable

6

hist(mtcars$mpg[mtcars$cyl == 6], main = paste(6, "cylinders"))

plot of chunk mpg-histogram-6

hist(mtcars$wt[mtcars$cyl == 6], main = paste(6, "cylinders"))

plot of chunk weight-histogam-6

4

hist(mtcars$mpg[mtcars$cyl == 4], main = paste(4, "cylinders"))

plot of chunk mpg-histogram-4

hist(mtcars$wt[mtcars$cyl == 4], main = paste(4, "cylinders"))

plot of chunk weight-histogam-4

8

hist(mtcars$mpg[mtcars$cyl == 8], main = paste(8, "cylinders"))

plot of chunk mpg-histogram-8

hist(mtcars$wt[mtcars$cyl == 8], main = paste(8, "cylinders"))

plot of chunk weight-histogam-8

# My report
```{r}
data(mtcars)
```
This example shows how to generate chunk labels dynamically with the brew syntax. It was motivated by the SO question: http://stackoverflow.com/q/12095113/559676
```{r create-iterator, include=FALSE}
src = NULL
pat_brew() # use brew syntax first
for (cur.cyl in unique(mtcars$cyl)) {
src = c(src, knit(text = readLines('041-label-i-child.tpl')))
}
# continue with markdown syntax and hooks
pat_md()
render_markdown()
# knit the generated R markdown source
out = knit(text = src)
```
## Generate report for each level of cylinder variable
```{r results='asis', echo=FALSE}
cat(out, sep = '\n')
```
\documentclass{article}
<<adjust-preamble, echo=FALSE, message=FALSE>>=
library(highlight)
opts_knit$set(use.highlight = TRUE)
knit_theme$set('acid')
opts_chunk$set(background='white') # R code use white background
@
\newcommand{\hlopt}[1]{\textcolor[rgb]{0,0,0}{#1}}
\usepackage{url}
\begin{document}
Normal R chunks.
<<test-R>>=
1+1
x=rnorm(5)
@
Highlight matlab chunks. Note you need to install highlight from \url{http://www.andre-simon.de}, and you probably need to put its binary path into PATH; otherwise just use the engine.path option, e.g.
\noindent\verb|<<engine='highlight', engine.path = 'full/path/to/highlight'>>=|
<<highlight, engine='highlight', engine.opts='-e acid -S matlab -O latex'>>=
function Y = kalmanM(pos)
dt=1;
%% Initialize state transition matrix
A=[ 1 0 dt 0 0 0;... % [x ]
0 1 0 dt 0 0;... % [y ]
0 0 1 0 dt 0;... % [Vx]
0 0 0 1 0 dt;... % [Vy]
0 0 0 0 1 0 ;... % [Ax]
0 0 0 0 0 1 ]; % [Ay]
% Initialize measurement matrix
H = [ 1 0 0 0 0 0; 0 1 0 0 0 0 ];
Q = eye(6);
R = 1000 * eye(2);
x_est = zeros(6, 1);
p_est = zeros(6, 6);
numPts = size(pos,1);
Y = zeros(numPts, 2);
for idx = 1:numPts
z = pos(idx, :)';
%% Predicted state and covariance
x_prd = A * x_est;
p_prd = A * p_est * A' + Q;
%% Estimation
S = H * p_prd' * H' + R;
B = H * p_prd';
klm_gain = (S \ B)';
%% Estimated state and covariance
x_est = x_prd + klm_gain * (z - H * x_prd);
p_est = p_prd - klm_gain * H * p_prd;
%% Compute the estimated measurements
Y(idx, :) = H * x_est;
end % of the function
end % of the function
@
\end{document}
\documentclass{article}\usepackage[]{graphicx}\usepackage[]{color}
%% maxwidth is the original width if it is less than linewidth
%% otherwise use linewidth (to make sure the graphics do not exceed the margin)
\makeatletter
\def\maxwidth{ %
\ifdim\Gin@nat@width>\linewidth
\linewidth
\else
\Gin@nat@width
\fi
}
\makeatother
\definecolor{fgcolor}{rgb}{0, 0, 0}
\newcommand{\hlnumber}[1]{\textcolor[rgb]{0.501960784313725,0,0.501960784313725}{#1}}%
\newcommand{\hlfunctioncall}[1]{\textcolor[rgb]{0,0.501960784313725,0.752941176470588}{\textbf{#1}}}%
\newcommand{\hlstring}[1]{\textcolor[rgb]{0.650980392156863,0.52156862745098,0}{#1}}%
\newcommand{\hlkeyword}[1]{\textcolor[rgb]{0.733333333333333,0.474509803921569,0.466666666666667}{\textbf{#1}}}%
\newcommand{\hlargument}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlcomment}[1]{\textcolor[rgb]{1,0.501960784313725,0}{#1}}%
\newcommand{\hlroxygencomment}[1]{\textcolor[rgb]{1,0.501960784313725,0}{#1}}%
\newcommand{\hlformalargs}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hleqformalargs}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlassignement}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlpackage}[1]{\textcolor[rgb]{0.501960784313725,0.501960784313725,0.752941176470588}{\textbf{#1}}}%
\newcommand{\hlslot}[1]{\textcolor[rgb]{0,0,0}{\textit{#1}}}%
\newcommand{\hlsymbol}[1]{\textcolor[rgb]{1,0,0.501960784313725}{#1}}%
\newcommand{\hlprompt}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\usepackage{framed}
\makeatletter
\newenvironment{kframe}{%
\def\at@end@of@kframe{}%
\ifinner\ifhmode%
\def\at@end@of@kframe{\end{minipage}}%
\begin{minipage}{\columnwidth}%
\fi\fi%
\def\FrameCommand##1{\hskip\@totalleftmargin \hskip-\fboxsep
\colorbox{shadecolor}{##1}\hskip-\fboxsep
% There is no \\@totalrightmargin, so:
\hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth}%
\MakeFramed {\advance\hsize-\width
\@totalleftmargin\z@ \linewidth\hsize
\@setminipage}}%
{\par\unskip\endMakeFramed%
\at@end@of@kframe}
\makeatother
\definecolor{shadecolor}{rgb}{.97, .97, .97}
\definecolor{messagecolor}{rgb}{0, 0, 0}
\definecolor{warningcolor}{rgb}{1, 0, 1}
\definecolor{errorcolor}{rgb}{1, 0, 0}
\newenvironment{knitrout}{}{} % an empty environment to be redefined in TeX
\usepackage{color}%
\newsavebox{\hlnormalsizeboxclosebrace}%
\newsavebox{\hlnormalsizeboxopenbrace}%
\newsavebox{\hlnormalsizeboxbackslash}%
\newsavebox{\hlnormalsizeboxlessthan}%
\newsavebox{\hlnormalsizeboxgreaterthan}%
\newsavebox{\hlnormalsizeboxdollar}%
\newsavebox{\hlnormalsizeboxunderscore}%
\newsavebox{\hlnormalsizeboxand}%
\newsavebox{\hlnormalsizeboxhash}%
\newsavebox{\hlnormalsizeboxat}%
\newsavebox{\hlnormalsizeboxpercent}%
\newsavebox{\hlnormalsizeboxhat}%
\newsavebox{\hlnormalsizeboxsinglequote}%
\newsavebox{\hlnormalsizeboxbacktick}%
\setbox\hlnormalsizeboxopenbrace=\hbox{\begin{normalsize}\verb.{.\end{normalsize}}%
\setbox\hlnormalsizeboxclosebrace=\hbox{\begin{normalsize}\verb.}.\end{normalsize}}%
\setbox\hlnormalsizeboxlessthan=\hbox{\begin{normalsize}\verb.<.\end{normalsize}}%
\setbox\hlnormalsizeboxdollar=\hbox{\begin{normalsize}\verb.$.\end{normalsize}}%
\setbox\hlnormalsizeboxunderscore=\hbox{\begin{normalsize}\verb._.\end{normalsize}}%
\setbox\hlnormalsizeboxand=\hbox{\begin{normalsize}\verb.&.\end{normalsize}}%
\setbox\hlnormalsizeboxhash=\hbox{\begin{normalsize}\verb.#.\end{normalsize}}%
\setbox\hlnormalsizeboxat=\hbox{\begin{normalsize}\verb.@.\end{normalsize}}%
\setbox\hlnormalsizeboxbackslash=\hbox{\begin{normalsize}\verb.\.\end{normalsize}}%
\setbox\hlnormalsizeboxgreaterthan=\hbox{\begin{normalsize}\verb.>.\end{normalsize}}%
\setbox\hlnormalsizeboxpercent=\hbox{\begin{normalsize}\verb.%.\end{normalsize}}%
\setbox\hlnormalsizeboxhat=\hbox{\begin{normalsize}\verb.^.\end{normalsize}}%
\setbox\hlnormalsizeboxsinglequote=\hbox{\begin{normalsize}\verb.'.\end{normalsize}}%
\setbox\hlnormalsizeboxbacktick=\hbox{\begin{normalsize}\verb.`.\end{normalsize}}%
\setbox\hlnormalsizeboxhat=\hbox{\begin{normalsize}\verb.^.\end{normalsize}}%
\newsavebox{\hltinyboxclosebrace}%
\newsavebox{\hltinyboxopenbrace}%
\newsavebox{\hltinyboxbackslash}%
\newsavebox{\hltinyboxlessthan}%
\newsavebox{\hltinyboxgreaterthan}%
\newsavebox{\hltinyboxdollar}%
\newsavebox{\hltinyboxunderscore}%
\newsavebox{\hltinyboxand}%
\newsavebox{\hltinyboxhash}%
\newsavebox{\hltinyboxat}%
\newsavebox{\hltinyboxpercent}%
\newsavebox{\hltinyboxhat}%
\newsavebox{\hltinyboxsinglequote}%
\newsavebox{\hltinyboxbacktick}%
\setbox\hltinyboxopenbrace=\hbox{\begin{tiny}\verb.{.\end{tiny}}%
\setbox\hltinyboxclosebrace=\hbox{\begin{tiny}\verb.}.\end{tiny}}%
\setbox\hltinyboxlessthan=\hbox{\begin{tiny}\verb.<.\end{tiny}}%
\setbox\hltinyboxdollar=\hbox{\begin{tiny}\verb.$.\end{tiny}}%
\setbox\hltinyboxunderscore=\hbox{\begin{tiny}\verb._.\end{tiny}}%
\setbox\hltinyboxand=\hbox{\begin{tiny}\verb.&.\end{tiny}}%
\setbox\hltinyboxhash=\hbox{\begin{tiny}\verb.#.\end{tiny}}%
\setbox\hltinyboxat=\hbox{\begin{tiny}\verb.@.\end{tiny}}%
\setbox\hltinyboxbackslash=\hbox{\begin{tiny}\verb.\.\end{tiny}}%
\setbox\hltinyboxgreaterthan=\hbox{\begin{tiny}\verb.>.\end{tiny}}%
\setbox\hltinyboxpercent=\hbox{\begin{tiny}\verb.%.\end{tiny}}%
\setbox\hltinyboxhat=\hbox{\begin{tiny}\verb.^.\end{tiny}}%
\setbox\hltinyboxsinglequote=\hbox{\begin{tiny}\verb.'.\end{tiny}}%
\setbox\hltinyboxbacktick=\hbox{\begin{tiny}\verb.`.\end{tiny}}%
\setbox\hltinyboxhat=\hbox{\begin{tiny}\verb.^.\end{tiny}}%
\newsavebox{\hlscriptsizeboxclosebrace}%
\newsavebox{\hlscriptsizeboxopenbrace}%
\newsavebox{\hlscriptsizeboxbackslash}%
\newsavebox{\hlscriptsizeboxlessthan}%
\newsavebox{\hlscriptsizeboxgreaterthan}%
\newsavebox{\hlscriptsizeboxdollar}%
\newsavebox{\hlscriptsizeboxunderscore}%
\newsavebox{\hlscriptsizeboxand}%
\newsavebox{\hlscriptsizeboxhash}%
\newsavebox{\hlscriptsizeboxat}%
\newsavebox{\hlscriptsizeboxpercent}%
\newsavebox{\hlscriptsizeboxhat}%
\newsavebox{\hlscriptsizeboxsinglequote}%
\newsavebox{\hlscriptsizeboxbacktick}%
\setbox\hlscriptsizeboxopenbrace=\hbox{\begin{scriptsize}\verb.{.\end{scriptsize}}%
\setbox\hlscriptsizeboxclosebrace=\hbox{\begin{scriptsize}\verb.}.\end{scriptsize}}%
\setbox\hlscriptsizeboxlessthan=\hbox{\begin{scriptsize}\verb.<.\end{scriptsize}}%
\setbox\hlscriptsizeboxdollar=\hbox{\begin{scriptsize}\verb.$.\end{scriptsize}}%
\setbox\hlscriptsizeboxunderscore=\hbox{\begin{scriptsize}\verb._.\end{scriptsize}}%
\setbox\hlscriptsizeboxand=\hbox{\begin{scriptsize}\verb.&.\end{scriptsize}}%
\setbox\hlscriptsizeboxhash=\hbox{\begin{scriptsize}\verb.#.\end{scriptsize}}%
\setbox\hlscriptsizeboxat=\hbox{\begin{scriptsize}\verb.@.\end{scriptsize}}%
\setbox\hlscriptsizeboxbackslash=\hbox{\begin{scriptsize}\verb.\.\end{scriptsize}}%
\setbox\hlscriptsizeboxgreaterthan=\hbox{\begin{scriptsize}\verb.>.\end{scriptsize}}%
\setbox\hlscriptsizeboxpercent=\hbox{\begin{scriptsize}\verb.%.\end{scriptsize}}%
\setbox\hlscriptsizeboxhat=\hbox{\begin{scriptsize}\verb.^.\end{scriptsize}}%
\setbox\hlscriptsizeboxsinglequote=\hbox{\begin{scriptsize}\verb.'.\end{scriptsize}}%
\setbox\hlscriptsizeboxbacktick=\hbox{\begin{scriptsize}\verb.`.\end{scriptsize}}%
\setbox\hlscriptsizeboxhat=\hbox{\begin{scriptsize}\verb.^.\end{scriptsize}}%
\newsavebox{\hlfootnotesizeboxclosebrace}%
\newsavebox{\hlfootnotesizeboxopenbrace}%
\newsavebox{\hlfootnotesizeboxbackslash}%
\newsavebox{\hlfootnotesizeboxlessthan}%
\newsavebox{\hlfootnotesizeboxgreaterthan}%
\newsavebox{\hlfootnotesizeboxdollar}%
\newsavebox{\hlfootnotesizeboxunderscore}%
\newsavebox{\hlfootnotesizeboxand}%
\newsavebox{\hlfootnotesizeboxhash}%
\newsavebox{\hlfootnotesizeboxat}%
\newsavebox{\hlfootnotesizeboxpercent}%
\newsavebox{\hlfootnotesizeboxhat}%
\newsavebox{\hlfootnotesizeboxsinglequote}%
\newsavebox{\hlfootnotesizeboxbacktick}%
\setbox\hlfootnotesizeboxopenbrace=\hbox{\begin{footnotesize}\verb.{.\end{footnotesize}}%
\setbox\hlfootnotesizeboxclosebrace=\hbox{\begin{footnotesize}\verb.}.\end{footnotesize}}%
\setbox\hlfootnotesizeboxlessthan=\hbox{\begin{footnotesize}\verb.<.\end{footnotesize}}%
\setbox\hlfootnotesizeboxdollar=\hbox{\begin{footnotesize}\verb.$.\end{footnotesize}}%
\setbox\hlfootnotesizeboxunderscore=\hbox{\begin{footnotesize}\verb._.\end{footnotesize}}%
\setbox\hlfootnotesizeboxand=\hbox{\begin{footnotesize}\verb.&.\end{footnotesize}}%
\setbox\hlfootnotesizeboxhash=\hbox{\begin{footnotesize}\verb.#.\end{footnotesize}}%
\setbox\hlfootnotesizeboxat=\hbox{\begin{footnotesize}\verb.@.\end{footnotesize}}%
\setbox\hlfootnotesizeboxbackslash=\hbox{\begin{footnotesize}\verb.\.\end{footnotesize}}%
\setbox\hlfootnotesizeboxgreaterthan=\hbox{\begin{footnotesize}\verb.>.\end{footnotesize}}%
\setbox\hlfootnotesizeboxpercent=\hbox{\begin{footnotesize}\verb.%.\end{footnotesize}}%
\setbox\hlfootnotesizeboxhat=\hbox{\begin{footnotesize}\verb.^.\end{footnotesize}}%
\setbox\hlfootnotesizeboxsinglequote=\hbox{\begin{footnotesize}\verb.'.\end{footnotesize}}%
\setbox\hlfootnotesizeboxbacktick=\hbox{\begin{footnotesize}\verb.`.\end{footnotesize}}%
\setbox\hlfootnotesizeboxhat=\hbox{\begin{footnotesize}\verb.^.\end{footnotesize}}%
\newsavebox{\hlsmallboxclosebrace}%
\newsavebox{\hlsmallboxopenbrace}%
\newsavebox{\hlsmallboxbackslash}%
\newsavebox{\hlsmallboxlessthan}%
\newsavebox{\hlsmallboxgreaterthan}%
\newsavebox{\hlsmallboxdollar}%
\newsavebox{\hlsmallboxunderscore}%
\newsavebox{\hlsmallboxand}%
\newsavebox{\hlsmallboxhash}%
\newsavebox{\hlsmallboxat}%
\newsavebox{\hlsmallboxpercent}%
\newsavebox{\hlsmallboxhat}%
\newsavebox{\hlsmallboxsinglequote}%
\newsavebox{\hlsmallboxbacktick}%
\setbox\hlsmallboxopenbrace=\hbox{\begin{small}\verb.{.\end{small}}%
\setbox\hlsmallboxclosebrace=\hbox{\begin{small}\verb.}.\end{small}}%
\setbox\hlsmallboxlessthan=\hbox{\begin{small}\verb.<.\end{small}}%
\setbox\hlsmallboxdollar=\hbox{\begin{small}\verb.$.\end{small}}%
\setbox\hlsmallboxunderscore=\hbox{\begin{small}\verb._.\end{small}}%
\setbox\hlsmallboxand=\hbox{\begin{small}\verb.&.\end{small}}%
\setbox\hlsmallboxhash=\hbox{\begin{small}\verb.#.\end{small}}%
\setbox\hlsmallboxat=\hbox{\begin{small}\verb.@.\end{small}}%
\setbox\hlsmallboxbackslash=\hbox{\begin{small}\verb.\.\end{small}}%
\setbox\hlsmallboxgreaterthan=\hbox{\begin{small}\verb.>.\end{small}}%
\setbox\hlsmallboxpercent=\hbox{\begin{small}\verb.%.\end{small}}%
\setbox\hlsmallboxhat=\hbox{\begin{small}\verb.^.\end{small}}%
\setbox\hlsmallboxsinglequote=\hbox{\begin{small}\verb.'.\end{small}}%
\setbox\hlsmallboxbacktick=\hbox{\begin{small}\verb.`.\end{small}}%
\setbox\hlsmallboxhat=\hbox{\begin{small}\verb.^.\end{small}}%
\newsavebox{\hllargeboxclosebrace}%
\newsavebox{\hllargeboxopenbrace}%
\newsavebox{\hllargeboxbackslash}%
\newsavebox{\hllargeboxlessthan}%
\newsavebox{\hllargeboxgreaterthan}%
\newsavebox{\hllargeboxdollar}%
\newsavebox{\hllargeboxunderscore}%
\newsavebox{\hllargeboxand}%
\newsavebox{\hllargeboxhash}%
\newsavebox{\hllargeboxat}%
\newsavebox{\hllargeboxpercent}%
\newsavebox{\hllargeboxhat}%
\newsavebox{\hllargeboxsinglequote}%
\newsavebox{\hllargeboxbacktick}%
\setbox\hllargeboxopenbrace=\hbox{\begin{large}\verb.{.\end{large}}%
\setbox\hllargeboxclosebrace=\hbox{\begin{large}\verb.}.\end{large}}%
\setbox\hllargeboxlessthan=\hbox{\begin{large}\verb.<.\end{large}}%
\setbox\hllargeboxdollar=\hbox{\begin{large}\verb.$.\end{large}}%
\setbox\hllargeboxunderscore=\hbox{\begin{large}\verb._.\end{large}}%
\setbox\hllargeboxand=\hbox{\begin{large}\verb.&.\end{large}}%
\setbox\hllargeboxhash=\hbox{\begin{large}\verb.#.\end{large}}%
\setbox\hllargeboxat=\hbox{\begin{large}\verb.@.\end{large}}%
\setbox\hllargeboxbackslash=\hbox{\begin{large}\verb.\.\end{large}}%
\setbox\hllargeboxgreaterthan=\hbox{\begin{large}\verb.>.\end{large}}%
\setbox\hllargeboxpercent=\hbox{\begin{large}\verb.%.\end{large}}%
\setbox\hllargeboxhat=\hbox{\begin{large}\verb.^.\end{large}}%
\setbox\hllargeboxsinglequote=\hbox{\begin{large}\verb.'.\end{large}}%
\setbox\hllargeboxbacktick=\hbox{\begin{large}\verb.`.\end{large}}%
\setbox\hllargeboxhat=\hbox{\begin{large}\verb.^.\end{large}}%
\newsavebox{\hlLargeboxclosebrace}%
\newsavebox{\hlLargeboxopenbrace}%
\newsavebox{\hlLargeboxbackslash}%
\newsavebox{\hlLargeboxlessthan}%
\newsavebox{\hlLargeboxgreaterthan}%
\newsavebox{\hlLargeboxdollar}%
\newsavebox{\hlLargeboxunderscore}%
\newsavebox{\hlLargeboxand}%
\newsavebox{\hlLargeboxhash}%
\newsavebox{\hlLargeboxat}%
\newsavebox{\hlLargeboxpercent}%
\newsavebox{\hlLargeboxhat}%
\newsavebox{\hlLargeboxsinglequote}%
\newsavebox{\hlLargeboxbacktick}%
\setbox\hlLargeboxopenbrace=\hbox{\begin{Large}\verb.{.\end{Large}}%
\setbox\hlLargeboxclosebrace=\hbox{\begin{Large}\verb.}.\end{Large}}%
\setbox\hlLargeboxlessthan=\hbox{\begin{Large}\verb.<.\end{Large}}%
\setbox\hlLargeboxdollar=\hbox{\begin{Large}\verb.$.\end{Large}}%
\setbox\hlLargeboxunderscore=\hbox{\begin{Large}\verb._.\end{Large}}%
\setbox\hlLargeboxand=\hbox{\begin{Large}\verb.&.\end{Large}}%
\setbox\hlLargeboxhash=\hbox{\begin{Large}\verb.#.\end{Large}}%
\setbox\hlLargeboxat=\hbox{\begin{Large}\verb.@.\end{Large}}%
\setbox\hlLargeboxbackslash=\hbox{\begin{Large}\verb.\.\end{Large}}%
\setbox\hlLargeboxgreaterthan=\hbox{\begin{Large}\verb.>.\end{Large}}%
\setbox\hlLargeboxpercent=\hbox{\begin{Large}\verb.%.\end{Large}}%
\setbox\hlLargeboxhat=\hbox{\begin{Large}\verb.^.\end{Large}}%
\setbox\hlLargeboxsinglequote=\hbox{\begin{Large}\verb.'.\end{Large}}%
\setbox\hlLargeboxbacktick=\hbox{\begin{Large}\verb.`.\end{Large}}%
\setbox\hlLargeboxhat=\hbox{\begin{Large}\verb.^.\end{Large}}%
\newsavebox{\hlLARGEboxclosebrace}%
\newsavebox{\hlLARGEboxopenbrace}%
\newsavebox{\hlLARGEboxbackslash}%
\newsavebox{\hlLARGEboxlessthan}%
\newsavebox{\hlLARGEboxgreaterthan}%
\newsavebox{\hlLARGEboxdollar}%
\newsavebox{\hlLARGEboxunderscore}%
\newsavebox{\hlLARGEboxand}%
\newsavebox{\hlLARGEboxhash}%
\newsavebox{\hlLARGEboxat}%
\newsavebox{\hlLARGEboxpercent}%
\newsavebox{\hlLARGEboxhat}%
\newsavebox{\hlLARGEboxsinglequote}%
\newsavebox{\hlLARGEboxbacktick}%
\setbox\hlLARGEboxopenbrace=\hbox{\begin{LARGE}\verb.{.\end{LARGE}}%
\setbox\hlLARGEboxclosebrace=\hbox{\begin{LARGE}\verb.}.\end{LARGE}}%
\setbox\hlLARGEboxlessthan=\hbox{\begin{LARGE}\verb.<.\end{LARGE}}%
\setbox\hlLARGEboxdollar=\hbox{\begin{LARGE}\verb.$.\end{LARGE}}%
\setbox\hlLARGEboxunderscore=\hbox{\begin{LARGE}\verb._.\end{LARGE}}%
\setbox\hlLARGEboxand=\hbox{\begin{LARGE}\verb.&.\end{LARGE}}%
\setbox\hlLARGEboxhash=\hbox{\begin{LARGE}\verb.#.\end{LARGE}}%
\setbox\hlLARGEboxat=\hbox{\begin{LARGE}\verb.@.\end{LARGE}}%
\setbox\hlLARGEboxbackslash=\hbox{\begin{LARGE}\verb.\.\end{LARGE}}%
\setbox\hlLARGEboxgreaterthan=\hbox{\begin{LARGE}\verb.>.\end{LARGE}}%
\setbox\hlLARGEboxpercent=\hbox{\begin{LARGE}\verb.%.\end{LARGE}}%
\setbox\hlLARGEboxhat=\hbox{\begin{LARGE}\verb.^.\end{LARGE}}%
\setbox\hlLARGEboxsinglequote=\hbox{\begin{LARGE}\verb.'.\end{LARGE}}%
\setbox\hlLARGEboxbacktick=\hbox{\begin{LARGE}\verb.`.\end{LARGE}}%
\setbox\hlLARGEboxhat=\hbox{\begin{LARGE}\verb.^.\end{LARGE}}%
\newsavebox{\hlhugeboxclosebrace}%
\newsavebox{\hlhugeboxopenbrace}%
\newsavebox{\hlhugeboxbackslash}%
\newsavebox{\hlhugeboxlessthan}%
\newsavebox{\hlhugeboxgreaterthan}%
\newsavebox{\hlhugeboxdollar}%
\newsavebox{\hlhugeboxunderscore}%
\newsavebox{\hlhugeboxand}%
\newsavebox{\hlhugeboxhash}%
\newsavebox{\hlhugeboxat}%
\newsavebox{\hlhugeboxpercent}%
\newsavebox{\hlhugeboxhat}%
\newsavebox{\hlhugeboxsinglequote}%
\newsavebox{\hlhugeboxbacktick}%
\setbox\hlhugeboxopenbrace=\hbox{\begin{huge}\verb.{.\end{huge}}%
\setbox\hlhugeboxclosebrace=\hbox{\begin{huge}\verb.}.\end{huge}}%
\setbox\hlhugeboxlessthan=\hbox{\begin{huge}\verb.<.\end{huge}}%
\setbox\hlhugeboxdollar=\hbox{\begin{huge}\verb.$.\end{huge}}%
\setbox\hlhugeboxunderscore=\hbox{\begin{huge}\verb._.\end{huge}}%
\setbox\hlhugeboxand=\hbox{\begin{huge}\verb.&.\end{huge}}%
\setbox\hlhugeboxhash=\hbox{\begin{huge}\verb.#.\end{huge}}%
\setbox\hlhugeboxat=\hbox{\begin{huge}\verb.@.\end{huge}}%
\setbox\hlhugeboxbackslash=\hbox{\begin{huge}\verb.\.\end{huge}}%
\setbox\hlhugeboxgreaterthan=\hbox{\begin{huge}\verb.>.\end{huge}}%
\setbox\hlhugeboxpercent=\hbox{\begin{huge}\verb.%.\end{huge}}%
\setbox\hlhugeboxhat=\hbox{\begin{huge}\verb.^.\end{huge}}%
\setbox\hlhugeboxsinglequote=\hbox{\begin{huge}\verb.'.\end{huge}}%
\setbox\hlhugeboxbacktick=\hbox{\begin{huge}\verb.`.\end{huge}}%
\setbox\hlhugeboxhat=\hbox{\begin{huge}\verb.^.\end{huge}}%
\newsavebox{\hlHugeboxclosebrace}%
\newsavebox{\hlHugeboxopenbrace}%
\newsavebox{\hlHugeboxbackslash}%
\newsavebox{\hlHugeboxlessthan}%
\newsavebox{\hlHugeboxgreaterthan}%
\newsavebox{\hlHugeboxdollar}%
\newsavebox{\hlHugeboxunderscore}%
\newsavebox{\hlHugeboxand}%
\newsavebox{\hlHugeboxhash}%
\newsavebox{\hlHugeboxat}%
\newsavebox{\hlHugeboxpercent}%
\newsavebox{\hlHugeboxhat}%
\newsavebox{\hlHugeboxsinglequote}%
\newsavebox{\hlHugeboxbacktick}%
\setbox\hlHugeboxopenbrace=\hbox{\begin{Huge}\verb.{.\end{Huge}}%
\setbox\hlHugeboxclosebrace=\hbox{\begin{Huge}\verb.}.\end{Huge}}%
\setbox\hlHugeboxlessthan=\hbox{\begin{Huge}\verb.<.\end{Huge}}%
\setbox\hlHugeboxdollar=\hbox{\begin{Huge}\verb.$.\end{Huge}}%
\setbox\hlHugeboxunderscore=\hbox{\begin{Huge}\verb._.\end{Huge}}%
\setbox\hlHugeboxand=\hbox{\begin{Huge}\verb.&.\end{Huge}}%
\setbox\hlHugeboxhash=\hbox{\begin{Huge}\verb.#.\end{Huge}}%
\setbox\hlHugeboxat=\hbox{\begin{Huge}\verb.@.\end{Huge}}%
\setbox\hlHugeboxbackslash=\hbox{\begin{Huge}\verb.\.\end{Huge}}%
\setbox\hlHugeboxgreaterthan=\hbox{\begin{Huge}\verb.>.\end{Huge}}%
\setbox\hlHugeboxpercent=\hbox{\begin{Huge}\verb.%.\end{Huge}}%
\setbox\hlHugeboxhat=\hbox{\begin{Huge}\verb.^.\end{Huge}}%
\setbox\hlHugeboxsinglequote=\hbox{\begin{Huge}\verb.'.\end{Huge}}%
\setbox\hlHugeboxbacktick=\hbox{\begin{Huge}\verb.`.\end{Huge}}%
\setbox\hlHugeboxhat=\hbox{\begin{Huge}\verb.^.\end{Huge}}%
\def\urltilda{\kern -.15em\lower .7ex\hbox{\~{}}\kern .04em}%
\newcommand{\hlstd}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlnum}[1]{\textcolor[rgb]{0.16,0.16,1}{#1}}
\newcommand{\hlesc}[1]{\textcolor[rgb]{1,0,1}{#1}}
\newcommand{\hlstr}[1]{\textcolor[rgb]{1,0,0}{#1}}
\newcommand{\hldstr}[1]{\textcolor[rgb]{0.51,0.51,0}{#1}}
\newcommand{\hlslc}[1]{\textcolor[rgb]{0.51,0.51,0.51}{\it{#1}}}
\newcommand{\hlcom}[1]{\textcolor[rgb]{0.51,0.51,0.51}{\it{#1}}}
\newcommand{\hldir}[1]{\textcolor[rgb]{0,0.51,0}{#1}}
\newcommand{\hlsym}[1]{\textcolor[rgb]{0,0,0}{#1}}
% \newcommand{\hlline}[1]{\textcolor[rgb]{0.33,0.33,0.33}{#1}}
\newcommand{\hlkwa}[1]{\textcolor[rgb]{0,0,0}{\bf{#1}}}
\newcommand{\hlkwb}[1]{\textcolor[rgb]{0.51,0,0}{#1}}
\newcommand{\hlkwc}[1]{\textcolor[rgb]{0,0,0}{\bf{#1}}}
\newcommand{\hlkwd}[1]{\textcolor[rgb]{0,0,0.51}{#1}}
\newcommand{\hlopt}[1]{\textcolor[rgb]{0,0,0}{#1}}
\usepackage{url}
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
\begin{document}
Normal R chunks.
\begin{knitrout}
\definecolor{shadecolor}{rgb}{1, 1, 1}\color{fgcolor}\begin{kframe}
\begin{flushleft}
\ttfamily\noindent
\hlnumber{1}{\ }\hlkeyword{+}{\ }\hlnumber{1}\mbox{}
\normalfont
\end{flushleft}
\begin{verbatim}
## [1] 2
\end{verbatim}
\begin{flushleft}
\ttfamily\noindent
\hlsymbol{x}{\ }\hlassignement{=}{\ }\hlfunctioncall{rnorm}\hlkeyword{(}\hlnumber{5}\hlkeyword{)}\mbox{}
\normalfont
\end{flushleft}
\end{kframe}
\end{knitrout}
Highlight matlab chunks. Note you need to install highlight from \url{http://www.andre-simon.de}, and you probably need to put its binary path into PATH; otherwise just use the engine.path option, e.g.
\noindent\verb|<<engine='highlight', engine.path = 'full/path/to/highlight'>>=|
\noindent
\ttfamily
\hlstd{}\hlkwa{function\ }\hlstd{Y\ }\hlopt{=\ }\hlstd{kalmanM}\hlopt{(}\hlstd{pos}\hlopt{)}\hspace*{\fill}\\
\hlstd{}\hlstd{\ \ }\hlstd{dt}\hlopt{=}\hlstd{}\hlnum{1}\hlstd{}\hlopt{;}\hspace*{\fill}\\
\hlstd{}\hlstd{\ \ }\hlstd{}\hlslc{\%\%\ Initialize\ state\ transition\ matrix}\hspace*{\fill}\\
\hlstd{}\hlstd{\ \ }\hlstd{A}\hlopt{={[}\ }\hlstd{}\hlnum{1\ 0\ }\hlstd{dt\ }\hlnum{0\ 0\ 0}\hlstd{}\hlopt{;}\hlstd{...}\hlstd{\ \ \ \ \ }\hlstd{}\hlslc{\%\ {[}x}\hlstd{\ \ }\hlslc{{]}}\hspace*{\fill}\\
\hlstd{}\hlstd{\ \ \ \ \ }\hlstd{}\hlnum{0\ 1\ 0\ }\hlstd{dt\ }\hlnum{0\ 0}\hlstd{}\hlopt{;}\hlstd{...}\hlstd{\ \ \ \ \ }\hlstd{}\hlslc{\%\ {[}y}\hlstd{\ \ }\hlslc{{]}}\hspace*{\fill}\\
\hlstd{}\hlstd{\ \ \ \ \ }\hlstd{}\hlnum{0\ 0\ 1\ 0\ }\hlstd{dt\ }\hlnum{0}\hlstd{}\hlopt{;}\hlstd{...}\hlstd{\ \ \ \ \ }\hlstd{}\hlslc{\%\ {[}Vx{]}}\hspace*{\fill}\\
\hlstd{}\hlstd{\ \ \ \ \ }\hlstd{}\hlnum{0\ 0\ 0\ 1\ 0\ }\hlstd{dt}\hlopt{;}\hlstd{...}\hlstd{\ \ \ \ \ }\hlstd{}\hlslc{\%\ {[}Vy{]}}\hspace*{\fill}\\
\hlstd{}\hlstd{\ \ \ \ \ }\hlstd{}\hlnum{0\ 0\ 0\ 0\ 1\ 0\ }\hlstd{}\hlopt{;}\hlstd{...}\hlstd{\ \ \ \ \ }\hlstd{}\hlslc{\%\ {[}Ax{]}}\hspace*{\fill}\\
\hlstd{}\hlstd{\ \ \ \ \ }\hlstd{}\hlnum{0\ 0\ 0\ 0\ 0\ 1\ }\hlstd{}\hlopt{{]};}\hlstd{\ \ \ \ \ \ \ }\hlopt{}\hlstd{}\hlslc{\%\ {[}Ay{]}}\hspace*{\fill}\\
\hlstd{}\hlstd{\ \ }\hlstd{}\hlslc{\%\ Initialize\ measurement\ matrix}\hspace*{\fill}\\
\hlstd{}\hlstd{\ \ }\hlstd{H\ }\hlopt{=\ {[}\ }\hlstd{}\hlnum{1\ 0\ 0\ 0\ 0\ 0}\hlstd{}\hlopt{;\ }\hlstd{}\hlnum{0\ 1\ 0\ 0\ 0\ 0\ }\hlstd{}\hlopt{{]};}\hspace*{\fill}\\
\hlstd{}\hlstd{\ \ }\hlstd{Q\ }\hlopt{=\ }\hlstd{eye}\hlopt{(}\hlstd{}\hlnum{6}\hlstd{}\hlopt{);}\hspace*{\fill}\\
\hlstd{}\hlstd{\ \ }\hlstd{R\ }\hlopt{=\ }\hlstd{}\hlnum{1000\ }\hlstd{}\hlopt{{*}\ }\hlstd{eye}\hlopt{(}\hlstd{}\hlnum{2}\hlstd{}\hlopt{);}\hspace*{\fill}\\
\hlstd{}\hlstd{\ \ }\hlstd{x\textunderscore est\ }\hlopt{=\ }\hlstd{zeros}\hlopt{(}\hlstd{}\hlnum{6}\hlstd{}\hlopt{,\ }\hlstd{}\hlnum{1}\hlstd{}\hlopt{);}\hspace*{\fill}\\
\hlstd{}\hlstd{\ \ }\hlstd{p\textunderscore est\ }\hlopt{=\ }\hlstd{zeros}\hlopt{(}\hlstd{}\hlnum{6}\hlstd{}\hlopt{,\ }\hlstd{}\hlnum{6}\hlstd{}\hlopt{);}\hspace*{\fill}\\
\hlstd{\hspace*{\fill}\\
}\hlstd{\ \ }\hlstd{numPts\ }\hlopt{=\ }\hlstd{}\hlkwa{size}\hlstd{}\hlopt{(}\hlstd{pos}\hlopt{,}\hlstd{}\hlnum{1}\hlstd{}\hlopt{);}\hspace*{\fill}\\
\hlstd{}\hlstd{\ \ }\hlstd{Y\ }\hlopt{=\ }\hlstd{zeros}\hlopt{(}\hlstd{numPts}\hlopt{,\ }\hlstd{}\hlnum{2}\hlstd{}\hlopt{);}\hspace*{\fill}\\
\hlstd{\hspace*{\fill}\\
}\hlstd{\ \ }\hlstd{}\hlkwa{for\ }\hlstd{idx\ }\hlopt{=\ }\hlstd{}\hlnum{1}\hlstd{}\hlopt{:}\hlstd{numPts\hspace*{\fill}\\
}\hlstd{\ \ \ \ }\hlstd{z\ }\hlopt{=\ }\hlstd{pos}\hlopt{(}\hlstd{idx}\hlopt{,\ :)}\hlstd{'}\hlopt{;}\hspace*{\fill}\\
\hlstd{\hspace*{\fill}\\
}\hlstd{\ \ \ \ }\hlstd{}\hlslc{\%\%\ Predicted\ state\ and\ covariance}\hspace*{\fill}\\
\hlstd{}\hlstd{\ \ \ \ }\hlstd{x\textunderscore prd\ }\hlopt{=\ }\hlstd{A\ }\hlopt{{*}\ }\hlstd{x\textunderscore est}\hlopt{;}\hspace*{\fill}\\
\hlstd{}\hlstd{\ \ \ \ }\hlstd{p\textunderscore prd\ }\hlopt{=\ }\hlstd{A\ }\hlopt{{*}\ }\hlstd{p\textunderscore est\ }\hlopt{{*}\ }\hlstd{A'\ }\hlopt{+\ }\hlstd{Q}\hlopt{;}\hspace*{\fill}\\
\hlstd{}\hlstd{\ \ \ \ }\hlstd{}\hlslc{\%\%\ Estimation}\hspace*{\fill}\\
\hlstd{}\hlstd{\ \ \ \ }\hlstd{S\ }\hlopt{=\ }\hlstd{H\ }\hlopt{{*}\ }\hlstd{p\textunderscore prd'\ }\hlopt{{*}\ }\hlstd{H'\ }\hlopt{+\ }\hlstd{R}\hlopt{;}\hspace*{\fill}\\
\hlstd{}\hlstd{\ \ \ \ }\hlstd{B\ }\hlopt{=\ }\hlstd{H\ }\hlopt{{*}\ }\hlstd{p\textunderscore prd'}\hlopt{;}\hspace*{\fill}\\
\hlstd{}\hlstd{\ \ \ \ }\hlstd{klm\textunderscore gain\ }\hlopt{=\ (}\hlstd{S\ $\backslash$\ B}\hlopt{)}\hlstd{'}\hlopt{;}\hspace*{\fill}\\
\hlstd{}\hlstd{\ \ \ \ }\hlstd{}\hlslc{\%\%\ Estimated\ state\ and\ covariance}\hspace*{\fill}\\
\hlstd{}\hlstd{\ \ \ \ }\hlstd{x\textunderscore est\ }\hlopt{=\ }\hlstd{x\textunderscore prd\ }\hlopt{+\ }\hlstd{klm\textunderscore gain\ }\hlopt{{*}\ (}\hlstd{z\ }\hlopt{{-}\ }\hlstd{H\ }\hlopt{{*}\ }\hlstd{x\textunderscore prd}\hlopt{);}\hspace*{\fill}\\
\hlstd{}\hlstd{\ \ \ \ }\hlstd{p\textunderscore est\ }\hlopt{=\ }\hlstd{p\textunderscore prd\ }\hlopt{{-}\ }\hlstd{klm\textunderscore gain\ }\hlopt{{*}\ }\hlstd{H\ }\hlopt{{*}\ }\hlstd{p\textunderscore prd}\hlopt{;}\hspace*{\fill}\\
\hlstd{}\hlstd{\ \ \ \ }\hlstd{}\hlslc{\%\%\ Compute\ the\ estimated\ measurements}\hspace*{\fill}\\
\hlstd{}\hlstd{\ \ \ \ }\hlstd{Y}\hlopt{(}\hlstd{idx}\hlopt{,\ :)\ =\ }\hlstd{H\ }\hlopt{{*}\ }\hlstd{x\textunderscore est}\hlopt{;}\hspace*{\fill}\\
\hlstd{}\hlstd{\ \ }\hlstd{}\hlkwa{end}\hlstd{\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ }\hlkwa{}\hlstd{}\hlslc{\%\ of\ the\ function}\hspace*{\fill}\\
\hlstd{}\hlkwa{end}\hlstd{\ \ \ }\hlkwa{}\hlstd{}\hlslc{\%\ of\ the\ function}\hlstd{}\hspace*{\fill}\\
\mbox{}
\normalfont
\normalsize
\end{document}
\documentclass{article}
\begin{document}
<<setup, include=FALSE>>=
knit_hooks$set(inline = function(x) gsub('%', '\\\\%', x))
@
\Sexpr{'hello %, are you still there?'}
\end{document}
\documentclass{article}\usepackage[]{graphicx}\usepackage[]{color}
%% maxwidth is the original width if it is less than linewidth
%% otherwise use linewidth (to make sure the graphics do not exceed the margin)
\makeatletter
\def\maxwidth{ %
\ifdim\Gin@nat@width>\linewidth
\linewidth
\else
\Gin@nat@width
\fi
}
\makeatother
\definecolor{fgcolor}{rgb}{0.2, 0.2, 0.2}
\newcommand{\hlnumber}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlfunctioncall}[1]{\textcolor[rgb]{0.501960784313725,0,0.329411764705882}{\textbf{#1}}}%
\newcommand{\hlstring}[1]{\textcolor[rgb]{0.6,0.6,1}{#1}}%
\newcommand{\hlkeyword}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlargument}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlcomment}[1]{\textcolor[rgb]{0.180392156862745,0.6,0.341176470588235}{#1}}%
\newcommand{\hlroxygencomment}[1]{\textcolor[rgb]{0.43921568627451,0.47843137254902,0.701960784313725}{#1}}%
\newcommand{\hlformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hleqformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlassignement}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlpackage}[1]{\textcolor[rgb]{0.588235294117647,0.709803921568627,0.145098039215686}{#1}}%
\newcommand{\hlslot}[1]{\textit{#1}}%
\newcommand{\hlsymbol}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlprompt}[1]{\textcolor[rgb]{0.2,0.2,0.2}{#1}}%
\usepackage{framed}
\makeatletter
\newenvironment{kframe}{%
\def\at@end@of@kframe{}%
\ifinner\ifhmode%
\def\at@end@of@kframe{\end{minipage}}%
\begin{minipage}{\columnwidth}%
\fi\fi%
\def\FrameCommand##1{\hskip\@totalleftmargin \hskip-\fboxsep
\colorbox{shadecolor}{##1}\hskip-\fboxsep
% There is no \\@totalrightmargin, so:
\hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth}%
\MakeFramed {\advance\hsize-\width
\@totalleftmargin\z@ \linewidth\hsize
\@setminipage}}%
{\par\unskip\endMakeFramed%
\at@end@of@kframe}
\makeatother
\definecolor{shadecolor}{rgb}{.97, .97, .97}
\definecolor{messagecolor}{rgb}{0, 0, 0}
\definecolor{warningcolor}{rgb}{1, 0, 1}
\definecolor{errorcolor}{rgb}{1, 0, 0}
\newenvironment{knitrout}{}{} % an empty environment to be redefined in TeX
\usepackage{alltt}
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
\begin{document}
hello \%, are you still there?
\end{document}
\documentclass{article}
\begin{document}
The size option controls the font size of chunks. This is the default size:
<<>>=
head(iris)
@
This is scriptsize:
<<size='scriptsize'>>=
head(iris)
@
The size does not work when results = 'asis':
<<test-asis, size='small', results='asis'>>=
cat(letters, sep = ' ')
@
But you can use a hook to add the size environment in this case:
<<setup, include=FALSE>>=
knit_hooks$set(size = function(before, options, envir) {
# bring back the size environment when results='asis'
if (options$results != 'asis') return()
paste('\\end{kframe}',
sprintf(if (before) '\\begin{%s}' else '\\end{%s}', options$size),
'\\begin{kframe}', sep = '')
})
@
<<ref.label='test-asis', size='scriptsize', results='asis'>>=
@
Move on!
\end{document}
\documentclass{article}\usepackage[]{graphicx}\usepackage[]{color}
%% maxwidth is the original width if it is less than linewidth
%% otherwise use linewidth (to make sure the graphics do not exceed the margin)
\makeatletter
\def\maxwidth{ %
\ifdim\Gin@nat@width>\linewidth
\linewidth
\else
\Gin@nat@width
\fi
}
\makeatother
\definecolor{fgcolor}{rgb}{0.2, 0.2, 0.2}
\newcommand{\hlnumber}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlfunctioncall}[1]{\textcolor[rgb]{0.501960784313725,0,0.329411764705882}{\textbf{#1}}}%
\newcommand{\hlstring}[1]{\textcolor[rgb]{0.6,0.6,1}{#1}}%
\newcommand{\hlkeyword}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlargument}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlcomment}[1]{\textcolor[rgb]{0.180392156862745,0.6,0.341176470588235}{#1}}%
\newcommand{\hlroxygencomment}[1]{\textcolor[rgb]{0.43921568627451,0.47843137254902,0.701960784313725}{#1}}%
\newcommand{\hlformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hleqformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlassignement}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlpackage}[1]{\textcolor[rgb]{0.588235294117647,0.709803921568627,0.145098039215686}{#1}}%
\newcommand{\hlslot}[1]{\textit{#1}}%
\newcommand{\hlsymbol}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlprompt}[1]{\textcolor[rgb]{0.2,0.2,0.2}{#1}}%
\usepackage{framed}
\makeatletter
\newenvironment{kframe}{%
\def\at@end@of@kframe{}%
\ifinner\ifhmode%
\def\at@end@of@kframe{\end{minipage}}%
\begin{minipage}{\columnwidth}%
\fi\fi%
\def\FrameCommand##1{\hskip\@totalleftmargin \hskip-\fboxsep
\colorbox{shadecolor}{##1}\hskip-\fboxsep
% There is no \\@totalrightmargin, so:
\hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth}%
\MakeFramed {\advance\hsize-\width
\@totalleftmargin\z@ \linewidth\hsize
\@setminipage}}%
{\par\unskip\endMakeFramed%
\at@end@of@kframe}
\makeatother
\definecolor{shadecolor}{rgb}{.97, .97, .97}
\definecolor{messagecolor}{rgb}{0, 0, 0}
\definecolor{warningcolor}{rgb}{1, 0, 1}
\definecolor{errorcolor}{rgb}{1, 0, 0}
\newenvironment{knitrout}{}{} % an empty environment to be redefined in TeX
\usepackage{alltt}
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
\begin{document}
The size option controls the font size of chunks. This is the default size:
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlfunctioncall{head}(iris)
\end{alltt}
\begin{verbatim}
## Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1 5.1 3.5 1.4 0.2 setosa
## 2 4.9 3.0 1.4 0.2 setosa
## 3 4.7 3.2 1.3 0.2 setosa
## 4 4.6 3.1 1.5 0.2 setosa
## 5 5.0 3.6 1.4 0.2 setosa
## 6 5.4 3.9 1.7 0.4 setosa
\end{verbatim}
\end{kframe}
\end{knitrout}
This is scriptsize:
\begin{knitrout}\scriptsize
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlfunctioncall{head}(iris)
\end{alltt}
\begin{verbatim}
## Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1 5.1 3.5 1.4 0.2 setosa
## 2 4.9 3.0 1.4 0.2 setosa
## 3 4.7 3.2 1.3 0.2 setosa
## 4 4.6 3.1 1.5 0.2 setosa
## 5 5.0 3.6 1.4 0.2 setosa
## 6 5.4 3.9 1.7 0.4 setosa
\end{verbatim}
\end{kframe}
\end{knitrout}
The size does not work when results = 'asis':
\begin{kframe}
\begin{alltt}
\hlfunctioncall{cat}(letters, sep = \hlstring{" "})
\end{alltt}
\end{kframe}a b c d e f g h i j k l m n o p q r s t u v w x y z
But you can use a hook to add the size environment in this case:
\begin{scriptsize}\begin{kframe}\begin{alltt}
\hlfunctioncall{cat}(letters, sep = \hlstring{" "})
\end{alltt}
\end{kframe}a b c d e f g h i j k l m n o p q r s t u v w x y z\end{scriptsize}
Move on!
\end{document}

Three arguments in chunk hooks

A chunk hook has three arguments: before, options and envir. We show how they work through some simple examples.

The before argument

It is a logical argument: before == TRUE executes code before a chunk.

knit_hooks$set(foo1 = function(before, options, envir) {
    if (before) {
        "_I appear before a chunk!_\n\n"
    } else {
        "\n\n_I am after a chunk..._"
    }
})

Test the foo1 hook:

I appear before a chunk!

1 + 1
## [1] 2

I am after a chunk...

The options argument

It contains all the chunk options (include global options) for the current chunk.

knit_hooks$set(foo2 = function(before, options, envir) {
    if (!before) {
        z = capture.output(str(options[c("eval", "dev", "results", "bar1", "bar2", 
            "bar3")]))
        z = paste("    ", z, sep = "", collapse = "\n")
        paste("Some chunk options in the above chunk are:\n\n", z, sep = "")
    }
})

Test the foo2 hook:

1 + 1
## [1] 2

Some chunk options in the above chunk are:

List of 6
 $ eval   : logi TRUE
 $ dev    : chr "png"
 $ results: chr "markup"
 $ bar1   : logi TRUE
 $ bar2   : chr "asdf"
 $ bar3   : num 3.14

The envir argument

It is the environment of the current chunk.

knit_hooks$set(foo3 = function(before, options, envir) {
    if (!before) {
        paste("Objects available in the above chunk:", paste("`", ls(envir), 
            "`", sep = "", collapse = ", "))
    }
})

Test the foo3 hook:

x2 = 1 + 1
y3 = rnorm(10)

Objects available in the above chunk: x2, y3

Another example:

knit_hooks$set(foo4 = function(before, options, envir) {
    if (!before && exists("z5", envir = envir)) {
        sprintf("**Ha! I see z5 = %.3f!**", envir$z5)
    }
})

Test foo4:

pi
## [1] 3.142

This above chunk is quiet because z5 does not exist yet.

z5 = 2 * pi

Ha! I see z5 = 6.283!

# Three arguments in chunk hooks
A chunk hook has three arguments: `before`, `options` and `envir`. We show how they work through some simple examples.
## The `before` argument
It is a logical argument: `before == TRUE` executes code before a chunk.
```{r}
knit_hooks$set(foo1 = function(before, options, envir) {
if (before) {
'_I appear before a chunk!_\n\n'
} else {
'\n\n_I am after a chunk..._'
}
})
```
Test the `foo1` hook:
```{r foo1='whatever'}
1+1
```
## The `options` argument
It contains all the chunk options (include global options) for the current chunk.
```{r}
knit_hooks$set(foo2 = function(before, options, envir) {
if (!before) {
z = capture.output(str(options[c('eval', 'dev', 'results', 'bar1', 'bar2', 'bar3')]))
z = paste(' ', z, sep = '', collapse = '\n')
paste('Some chunk options in the above chunk are:\n\n', z, sep = '')
}
})
```
Test the `foo2` hook:
```{r foo2='hi', bar1=TRUE, bar2='asdf', bar3=3.14159}
1+1
```
## The `envir` argument
It is the environment of the current chunk.
```{r}
knit_hooks$set(foo3 = function(before, options, envir) {
if (!before) {
paste('Objects available in the above chunk:',
paste('`', ls(envir), '`', sep = '', collapse = ', '))
}
})
```
Test the `foo3` hook:
```{r foo3=TRUE}
x2=1+1; y3=rnorm(10)
```
Another example:
```{r}
knit_hooks$set(foo4 = function(before, options, envir) {
if (!before && exists('z5', envir = envir)) {
sprintf('**Ha! I see z5 = %.3f!**', envir$z5)
}
})
```
Test `foo4`:
```{r foo4='qwer'}
pi
```
This above chunk is quiet because `z5` does not exist yet.
```{r foo4='asdf'}
z5=2*pi
```

This demo shows you how to reference code in a URL. We use R-Forge as an example, but you can really read code from anywhere.

We cache this chunk so that the next time we compile this document, the code does not need to be read from the web again.

demo.sub = read_rforge("rgl/demo/subdivision.r", project = "rgl")
head(demo.sub)
## [1] "# RGL-demo: subdivision surfaces"  
## [2] "# author: Daniel Adler"            
## [3] "# $Id$"                            
## [4] ""                                  
## [5] "rgl.demo.subdivision <- function()"
## [6] "{"

Once we have the source code, we can insert it into knitr with read_chunk():

read_chunk(lines = demo.sub, labels = "rgl-sub")

That means we assigned the code to a chunk named rgl-sub, which appears below:

# RGL-demo: subdivision surfaces author: Daniel Adler $Id$

rgl.demo.subdivision <- function() {
    # setup environment
    clear3d("all")
    view3d()
    bg3d(color = "gray")
    light3d()
    
    # generate basic mesh
    obj <- oh3d()
    
    part <- function(level, tx, ...) {
        shade3d(translate3d(obj, tx, 0, 0), color = "gray30", front = "lines", 
            alpha = 0.5, back = "lines", override = TRUE)
        shade3d(translate3d(subdivision3d(obj, depth = level), tx, 0, 0), override = TRUE, 
            ...)
    }
    
    common <- c(alpha = 0.5)
    
    part(0, -5.5, color = "blue", common)
    part(1, -1.75, color = "yellow", common)
    part(2, 1.75, color = "red", common)
    part(3, 5.5, color = "green", common)
    
}

open3d()
rgl.demo.subdivision()

You can actually run the code and capture the rgl plot, but before that we need to load the package and set a rgl hook:

library(rgl)
knit_hooks$set(rgl = hook_rgl)

Now you can see the 3D plot:

open3d()
rgl.demo.subdivision()

plot of chunk rgl-sub

This demo shows you how to reference code in a URL. We use R-Forge as an example, but you can really read code from anywhere.
We cache this chunk so that the next time we compile this document, the code does not need to be read from the web again.
```{r read-code, cache=TRUE}
demo.sub = read_rforge('rgl/demo/subdivision.r', project = 'rgl')
head(demo.sub)
```
Once we have the source code, we can insert it into **knitr** with `read_chunk()`:
```{r}
read_chunk(lines = demo.sub, labels = 'rgl-sub')
```
That means we assigned the code to a chunk named `rgl-sub`, which appears below:
```{r rgl-sub, eval=FALSE}
```
You can actually run the code and capture the rgl plot, but before that we need to load the package and set a rgl hook:
```{r}
library(rgl)
knit_hooks$set(rgl = hook_rgl)
```
Now you can see the 3D plot:
```{r rgl-sub, rgl=TRUE, fig.height=4, fig.width=4, echo=-(1:4), results='hide', cache=TRUE}
```
\documentclass{article}
% you do not really need this, since png has higher priority to pdf by default
\DeclareGraphicsExtensions{.png,.pdf,.jpeg,.jpg}
\begin{document}
This is an example showing you how to convert PDF figures generated by tikz to PNG via ImageMagick:
<<setup, include=FALSE>>=
opts_chunk$set(cache=TRUE)
options(width = 60)
knit_hooks$set(tikz2png = function(before, options, envir) {
# use this hook only for dev='tikz' and externalized tikz graphics
if (before || options$dev != 'tikz' || !options$external || options$fig.num == 0) return()
figs = knitr:::all_figs(options, ext = 'pdf') # all figure names
# note the tikz2png option is the extra parameters passed to 'convert'
for (fig in figs) {
system(sprintf('convert %s %s %s', options$tikz2png, fig, sub('\\.pdf$', '.png', fig)))
}
})
@
The plot in this chunk is converted to PNG:
<<test-a, dev='tikz', fig.width=4.4, fig.height=3.3, tikz2png='-density 300'>>=
(x=rnorm(20))
par(mar = c(4.5, 4, .1, .1))
hist(x, main='', xlab='$x$ (how the fonts look like here?)',
ylab='$\\hat{f}(x) = \\frac{1}{nh}\\sum_{i=1}^n \\cdots$')
@
This chunk uses the PDF device, and it is not converted:
<<test-b, dev='pdf', fig.height=3>>=
par(mar = c(4.5, 4, .1, .1))
plot(x, pch = 19)
@
\end{document}
\documentclass{article}\usepackage[]{graphicx}\usepackage[]{color}
%% maxwidth is the original width if it is less than linewidth
%% otherwise use linewidth (to make sure the graphics do not exceed the margin)
\makeatletter
\def\maxwidth{ %
\ifdim\Gin@nat@width>\linewidth
\linewidth
\else
\Gin@nat@width
\fi
}
\makeatother
\definecolor{fgcolor}{rgb}{0.2, 0.2, 0.2}
\newcommand{\hlnumber}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlfunctioncall}[1]{\textcolor[rgb]{0.501960784313725,0,0.329411764705882}{\textbf{#1}}}%
\newcommand{\hlstring}[1]{\textcolor[rgb]{0.6,0.6,1}{#1}}%
\newcommand{\hlkeyword}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlargument}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlcomment}[1]{\textcolor[rgb]{0.180392156862745,0.6,0.341176470588235}{#1}}%
\newcommand{\hlroxygencomment}[1]{\textcolor[rgb]{0.43921568627451,0.47843137254902,0.701960784313725}{#1}}%
\newcommand{\hlformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hleqformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlassignement}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlpackage}[1]{\textcolor[rgb]{0.588235294117647,0.709803921568627,0.145098039215686}{#1}}%
\newcommand{\hlslot}[1]{\textit{#1}}%
\newcommand{\hlsymbol}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlprompt}[1]{\textcolor[rgb]{0.2,0.2,0.2}{#1}}%
\usepackage{framed}
\makeatletter
\newenvironment{kframe}{%
\def\at@end@of@kframe{}%
\ifinner\ifhmode%
\def\at@end@of@kframe{\end{minipage}}%
\begin{minipage}{\columnwidth}%
\fi\fi%
\def\FrameCommand##1{\hskip\@totalleftmargin \hskip-\fboxsep
\colorbox{shadecolor}{##1}\hskip-\fboxsep
% There is no \\@totalrightmargin, so:
\hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth}%
\MakeFramed {\advance\hsize-\width
\@totalleftmargin\z@ \linewidth\hsize
\@setminipage}}%
{\par\unskip\endMakeFramed%
\at@end@of@kframe}
\makeatother
\definecolor{shadecolor}{rgb}{.97, .97, .97}
\definecolor{messagecolor}{rgb}{0, 0, 0}
\definecolor{warningcolor}{rgb}{1, 0, 1}
\definecolor{errorcolor}{rgb}{1, 0, 0}
\newenvironment{knitrout}{}{} % an empty environment to be redefined in TeX
\usepackage{alltt}
% you do not really need this, since png has higher priority to pdf by default
\DeclareGraphicsExtensions{.png,.pdf,.jpeg,.jpg}
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
\begin{document}
This is an example showing you how to convert PDF figures generated by tikz to PNG via ImageMagick:
The plot in this chunk is converted to PNG:
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
(x = \hlfunctioncall{rnorm}(20))
\end{alltt}
\begin{verbatim}
## [1] -0.56048 -0.23018 1.55871 0.07051 0.12929 1.71506
## [7] 0.46092 -1.26506 -0.68685 -0.44566 1.22408 0.35981
## [13] 0.40077 0.11068 -0.55584 1.78691 0.49785 -1.96662
## [19] 0.70136 -0.47279
\end{verbatim}
\begin{alltt}
\hlfunctioncall{par}(mar = \hlfunctioncall{c}(4.5, 4, 0.1, 0.1))
\hlfunctioncall{hist}(x, main = \hlstring{""}, xlab = \hlstring{"$x$ (how the fonts look like here?)"},
ylab = \hlstring{"$\textbackslash{}\textbackslash{}hat\{f\}(x) = \textbackslash{}\textbackslash{}frac\{1\}\{nh\}\textbackslash{}\textbackslash{}sum_\{i=1\}^n \textbackslash{}\textbackslash{}cdots$"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/047-tikz-png-test-a}
\end{knitrout}
This chunk uses the PDF device, and it is not converted:
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlfunctioncall{par}(mar = \hlfunctioncall{c}(4.5, 4, 0.1, 0.1))
\hlfunctioncall{plot}(x, pch = 19)
\end{alltt}
\end{kframe}\includegraphics[width=\maxwidth]{figure/047-tikz-png-test-b}
\end{knitrout}
\end{document}
\documentclass{article}
\begin{document}
\title{A Minimal Example}
\author{Yihui Xie}
\maketitle
We examine the relationship between speed and stopping
distance using a linear regression model:
$Y = \beta_0 + \beta_1 x + \epsilon$.
<<model, fig.width=4, fig.height=3, fig.align='center'>>=
par(mar = c(4, 4, 1, 1), mgp = c(2, 1, 0), cex = 0.8)
plot(cars, pch = 20, col = 'darkgray')
fit <- lm(dist ~ speed, data = cars)
abline(fit, lwd = 2)
@
The slope of a simple linear regression is
\Sexpr{coef(fit)[2]}.
\end{document}
\documentclass{article}\usepackage[]{graphicx}\usepackage[]{color}
%% maxwidth is the original width if it is less than linewidth
%% otherwise use linewidth (to make sure the graphics do not exceed the margin)
\makeatletter
\def\maxwidth{ %
\ifdim\Gin@nat@width>\linewidth
\linewidth
\else
\Gin@nat@width
\fi
}
\makeatother
\definecolor{fgcolor}{rgb}{0.2, 0.2, 0.2}
\newcommand{\hlnumber}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlfunctioncall}[1]{\textcolor[rgb]{0.501960784313725,0,0.329411764705882}{\textbf{#1}}}%
\newcommand{\hlstring}[1]{\textcolor[rgb]{0.6,0.6,1}{#1}}%
\newcommand{\hlkeyword}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlargument}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlcomment}[1]{\textcolor[rgb]{0.180392156862745,0.6,0.341176470588235}{#1}}%
\newcommand{\hlroxygencomment}[1]{\textcolor[rgb]{0.43921568627451,0.47843137254902,0.701960784313725}{#1}}%
\newcommand{\hlformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hleqformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlassignement}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlpackage}[1]{\textcolor[rgb]{0.588235294117647,0.709803921568627,0.145098039215686}{#1}}%
\newcommand{\hlslot}[1]{\textit{#1}}%
\newcommand{\hlsymbol}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlprompt}[1]{\textcolor[rgb]{0.2,0.2,0.2}{#1}}%
\usepackage{framed}
\makeatletter
\newenvironment{kframe}{%
\def\at@end@of@kframe{}%
\ifinner\ifhmode%
\def\at@end@of@kframe{\end{minipage}}%
\begin{minipage}{\columnwidth}%
\fi\fi%
\def\FrameCommand##1{\hskip\@totalleftmargin \hskip-\fboxsep
\colorbox{shadecolor}{##1}\hskip-\fboxsep
% There is no \\@totalrightmargin, so:
\hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth}%
\MakeFramed {\advance\hsize-\width
\@totalleftmargin\z@ \linewidth\hsize
\@setminipage}}%
{\par\unskip\endMakeFramed%
\at@end@of@kframe}
\makeatother
\definecolor{shadecolor}{rgb}{.97, .97, .97}
\definecolor{messagecolor}{rgb}{0, 0, 0}
\definecolor{warningcolor}{rgb}{1, 0, 1}
\definecolor{errorcolor}{rgb}{1, 0, 0}
\newenvironment{knitrout}{}{} % an empty environment to be redefined in TeX
\usepackage{alltt}
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
\begin{document}
\title{A Minimal Example}
\author{Yihui Xie}
\maketitle
We examine the relationship between speed and stopping
distance using a linear regression model:
$Y = \beta_0 + \beta_1 x + \epsilon$.
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlfunctioncall{par}(mar = \hlfunctioncall{c}(4, 4, 1, 1), mgp = \hlfunctioncall{c}(2, 1, 0), cex = 0.8)
\hlfunctioncall{plot}(cars, pch = 20, col = \hlstring{"darkgray"})
fit <- \hlfunctioncall{lm}(dist ~ speed, data = cars)
\hlfunctioncall{abline}(fit, lwd = 2)
\end{alltt}
\end{kframe}
{\centering \includegraphics[width=\maxwidth]{figure/048-cars-demo-model}
}
\end{knitrout}
The slope of a simple linear regression is
3.9324.
\end{document}

A Minimal Example

We examine the relationship between speed and stopping distance using a linear regression model: $Y = \beta_0 + \beta_1 x + \epsilon$.

par(mar = c(4, 4, 1, 1), mgp = c(2, 1, 0), cex = 0.8)
plot(cars, pch = 20, col = "darkgray")
fit <- lm(dist ~ speed, data = cars)
abline(fit, lwd = 2)

plot of chunk model

The slope of a simple linear regression is 3.9324.

# A Minimal Example
We examine the relationship between speed and stopping
distance using a linear regression model:
$Y = \beta_0 + \beta_1 x + \epsilon$.
```{r model, fig.width=4, fig.height=3, fig.align='center'}
par(mar = c(4, 4, 1, 1), mgp = c(2, 1, 0), cex = 0.8)
plot(cars, pch = 20, col = 'darkgray')
fit <- lm(dist ~ speed, data = cars)
abline(fit, lwd = 2)
```
The slope of a simple linear regression is `r coef(fit)[2]`.
\documentclass{beamer}
\title{Test framebreaks}
\author{Yihui Xie}
\begin{document}
\maketitle
<<setup, include=FALSE>>=
# the kframe environment does not work with allowframebreaks, so remove it
knit_hooks$set(document = function(x) {
gsub('\\\\(begin|end)\\{kframe\\}', '', x)
})
@
\begin{frame}[allowframebreaks,fragile]
\frametitle{Preliminaries}
<<step0,size="footnotesize",out.width=".7\\linewidth">>=
example(step)
@
\end{frame}
\end{document}
\documentclass{beamer}\usepackage[]{graphicx}\usepackage[]{color}
%% maxwidth is the original width if it is less than linewidth
%% otherwise use linewidth (to make sure the graphics do not exceed the margin)
\makeatletter
\def\maxwidth{ %
\ifdim\Gin@nat@width>\linewidth
\linewidth
\else
\Gin@nat@width
\fi
}
\makeatother
\definecolor{fgcolor}{rgb}{0.2, 0.2, 0.2}
\newcommand{\hlnumber}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlfunctioncall}[1]{\textcolor[rgb]{0.501960784313725,0,0.329411764705882}{\textbf{#1}}}%
\newcommand{\hlstring}[1]{\textcolor[rgb]{0.6,0.6,1}{#1}}%
\newcommand{\hlkeyword}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlargument}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlcomment}[1]{\textcolor[rgb]{0.180392156862745,0.6,0.341176470588235}{#1}}%
\newcommand{\hlroxygencomment}[1]{\textcolor[rgb]{0.43921568627451,0.47843137254902,0.701960784313725}{#1}}%
\newcommand{\hlformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hleqformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlassignement}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlpackage}[1]{\textcolor[rgb]{0.588235294117647,0.709803921568627,0.145098039215686}{#1}}%
\newcommand{\hlslot}[1]{\textit{#1}}%
\newcommand{\hlsymbol}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlprompt}[1]{\textcolor[rgb]{0.2,0.2,0.2}{#1}}%
\usepackage{framed}
\makeatletter
\newenvironment{kframe}{%
\def\at@end@of@kframe{}%
\ifinner\ifhmode%
\def\at@end@of@kframe{\end{minipage}}%
\begin{minipage}{\columnwidth}%
\fi\fi%
\def\FrameCommand##1{\hskip\@totalleftmargin \hskip-\fboxsep
\colorbox{shadecolor}{##1}\hskip-\fboxsep
% There is no \\@totalrightmargin, so:
\hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth}%
\MakeFramed {\advance\hsize-\width
\@totalleftmargin\z@ \linewidth\hsize
\@setminipage}}%
{\par\unskip\endMakeFramed%
\at@end@of@kframe}
\makeatother
\definecolor{shadecolor}{rgb}{.97, .97, .97}
\definecolor{messagecolor}{rgb}{0, 0, 0}
\definecolor{warningcolor}{rgb}{1, 0, 1}
\definecolor{errorcolor}{rgb}{1, 0, 0}
\newenvironment{knitrout}{}{} % an empty environment to be redefined in TeX
\usepackage{alltt}
\title{Test framebreaks}
\author{Yihui Xie}
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
\begin{document}
\maketitle
\begin{frame}[allowframebreaks,fragile]
\frametitle{Preliminaries}
\begin{knitrout}\footnotesize
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}
\begin{alltt}
\hlfunctioncall{example}(step)
\end{alltt}
\begin{verbatim}
##
## step> ## No test:
## step> ## following on from example(lm)
## step> ## Don't show:
## step> utils::example("lm", echo = FALSE)
\end{verbatim}
\includegraphics[width=.7\linewidth]{figure/050-allowframebreaks-step0}
\begin{verbatim}
##
## step> ## End Don't show
## step> step(lm.D9)
## Start: AIC=-12.58
## weight ~ group
##
## Df Sum of Sq RSS AIC
## - group 1 0.688 9.42 -13.1
## <none> 8.73 -12.6
##
## Step: AIC=-13.06
## weight ~ 1
##
##
## Call:
## lm(formula = weight ~ 1)
##
## Coefficients:
## (Intercept)
## 4.85
##
##
## step> summary(lm1 <- lm(Fertility ~ ., data = swiss))
##
## Call:
## lm(formula = Fertility ~ ., data = swiss)
##
## Residuals:
## Min 1Q Median 3Q Max
## -15.274 -5.262 0.503 4.120 15.321
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 66.9152 10.7060 6.25 1.9e-07 ***
## Agriculture -0.1721 0.0703 -2.45 0.0187 *
## Examination -0.2580 0.2539 -1.02 0.3155
## Education -0.8709 0.1830 -4.76 2.4e-05 ***
## Catholic 0.1041 0.0353 2.95 0.0052 **
## Infant.Mortality 1.0770 0.3817 2.82 0.0073 **
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 7.17 on 41 degrees of freedom
## Multiple R-squared: 0.707, Adjusted R-squared: 0.671
## F-statistic: 19.8 on 5 and 41 DF, p-value: 5.59e-10
##
##
## step> slm1 <- step(lm1)
## Start: AIC=190.7
## Fertility ~ Agriculture + Examination + Education + Catholic +
## Infant.Mortality
##
## Df Sum of Sq RSS AIC
## - Examination 1 53 2158 190
## <none> 2105 191
## - Agriculture 1 308 2413 195
## - Infant.Mortality 1 409 2514 197
## - Catholic 1 448 2553 198
## - Education 1 1163 3268 209
##
## Step: AIC=189.9
## Fertility ~ Agriculture + Education + Catholic + Infant.Mortality
##
## Df Sum of Sq RSS AIC
## <none> 2158 190
## - Agriculture 1 264 2422 193
## - Infant.Mortality 1 410 2568 196
## - Catholic 1 957 3115 205
## - Education 1 2250 4408 221
##
## step> summary(slm1)
##
## Call:
## lm(formula = Fertility ~ Agriculture + Education + Catholic +
## Infant.Mortality, data = swiss)
##
## Residuals:
## Min 1Q Median 3Q Max
## -14.676 -6.052 0.751 3.166 16.142
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 62.1013 9.6049 6.47 8.5e-08 ***
## Agriculture -0.1546 0.0682 -2.27 0.0286 *
## Education -0.9803 0.1481 -6.62 5.1e-08 ***
## Catholic 0.1247 0.0289 4.31 9.5e-05 ***
## Infant.Mortality 1.0784 0.3819 2.82 0.0072 **
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 7.17 on 42 degrees of freedom
## Multiple R-squared: 0.699, Adjusted R-squared: 0.671
## F-statistic: 24.4 on 4 and 42 DF, p-value: 1.72e-10
##
##
## step> slm1$anova
## Step Df Deviance Resid. Df Resid. Dev AIC
## 1 NA NA 41 2105 190.7
## 2 - Examination 1 53.03 42 2158 189.9
##
## step> ## End(No test)
## step>
## step>
\end{verbatim}
\end{knitrout}
\end{frame}
\end{document}
\documentclass{article}
\begin{document}
<<read-demo>>=
library(diagram)
read_demo('flowchart', package = 'diagram',
labels = 'demo-flowchart')
<<demo-flowchart, dev='tikz', cache=TRUE>>=
@
\end{document}
\documentclass{article}\usepackage[]{graphicx}\usepackage[]{color}
%% maxwidth is the original width if it is less than linewidth
%% otherwise use linewidth (to make sure the graphics do not exceed the margin)
\makeatletter
\def\maxwidth{ %
\ifdim\Gin@nat@width>\linewidth
\linewidth
\else
\Gin@nat@width
\fi
}
\makeatother
\definecolor{fgcolor}{rgb}{0.2, 0.2, 0.2}
\newcommand{\hlnumber}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlfunctioncall}[1]{\textcolor[rgb]{0.501960784313725,0,0.329411764705882}{\textbf{#1}}}%
\newcommand{\hlstring}[1]{\textcolor[rgb]{0.6,0.6,1}{#1}}%
\newcommand{\hlkeyword}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlargument}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlcomment}[1]{\textcolor[rgb]{0.180392156862745,0.6,0.341176470588235}{#1}}%
\newcommand{\hlroxygencomment}[1]{\textcolor[rgb]{0.43921568627451,0.47843137254902,0.701960784313725}{#1}}%
\newcommand{\hlformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hleqformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlassignement}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlpackage}[1]{\textcolor[rgb]{0.588235294117647,0.709803921568627,0.145098039215686}{#1}}%
\newcommand{\hlslot}[1]{\textit{#1}}%
\newcommand{\hlsymbol}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlprompt}[1]{\textcolor[rgb]{0.2,0.2,0.2}{#1}}%
\usepackage{framed}
\makeatletter
\newenvironment{kframe}{%
\def\at@end@of@kframe{}%
\ifinner\ifhmode%
\def\at@end@of@kframe{\end{minipage}}%
\begin{minipage}{\columnwidth}%
\fi\fi%
\def\FrameCommand##1{\hskip\@totalleftmargin \hskip-\fboxsep
\colorbox{shadecolor}{##1}\hskip-\fboxsep
% There is no \\@totalrightmargin, so:
\hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth}%
\MakeFramed {\advance\hsize-\width
\@totalleftmargin\z@ \linewidth\hsize
\@setminipage}}%
{\par\unskip\endMakeFramed%
\at@end@of@kframe}
\makeatother
\definecolor{shadecolor}{rgb}{.97, .97, .97}
\definecolor{messagecolor}{rgb}{0, 0, 0}
\definecolor{warningcolor}{rgb}{1, 0, 1}
\definecolor{errorcolor}{rgb}{1, 0, 0}
\newenvironment{knitrout}{}{} % an empty environment to be redefined in TeX
\usepackage{alltt}
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
\begin{document}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlfunctioncall{library}(diagram)
\end{alltt}
{\ttfamily\noindent\itshape\color{messagecolor}{\#\# Loading required package: shape}}\begin{alltt}
\hlfunctioncall{read_demo}(\hlstring{"flowchart"}, package = \hlstring{"diagram"}, labels = \hlstring{"demo-flowchart"})
\end{alltt}
\end{kframe}
\end{knitrout}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlcomment{## Flowchart examples}
\hlfunctioncall{par}(ask = TRUE)
\hlcomment{## MODELLING DIAGRAM}
mar <- \hlfunctioncall{par}(mar = \hlfunctioncall{c}(1, 1, 1, 1))
\hlfunctioncall{openplotmat}(main = \hlstring{"from Soetaert and herman, book in prep"}, cex.main = 1)
elpos <- \hlfunctioncall{coordinates}(\hlfunctioncall{c}(1, 1, 1, 1, 1, 1, 1, 1), mx = -0.1)
\hlfunctioncall{segmentarrow}(elpos[7, ], elpos[2, ], arr.pos = 0.15, dd = 0.3, arr.side = 3,
endhead = TRUE)
\hlfunctioncall{segmentarrow}(elpos[7, ], elpos[3, ], arr.pos = 0.15, dd = 0.3, arr.side = 3,
endhead = TRUE)
\hlfunctioncall{segmentarrow}(elpos[7, ], elpos[4, ], arr.pos = 0.15, dd = 0.3, arr.side = 3,
endhead = TRUE)
pin <- \hlfunctioncall{par}(\hlstring{"pin"}) # size of plotting region, inches
xx <- 0.2
yy <- xx * pin[1]/pin[2] * 0.15 \hlcomment{# used to make circles round}
sx <- \hlfunctioncall{rep}(xx, 8)
sx[7] <- 0.05
sy <- \hlfunctioncall{rep}(yy, 8)
sy[6] <- yy * 1.5
sy[7] <- sx[7] * pin[1]/pin[2]
\hlfunctioncall{for} (i in \hlfunctioncall{c}(1:7)) \hlfunctioncall{straightarrow}(to = elpos[i + 1, ], from = elpos[i, ], lwd = 2,
arr.pos = 0.6, endhead = TRUE)
lab <- \hlfunctioncall{c}(\hlstring{"Problem"}, \hlstring{"Conceptual model"}, \hlstring{"Mathematical model"}, \hlstring{"Parameterisation"},
\hlstring{"Mathematical solution"}, \hlstring{""}, \hlstring{"OK?"}, \hlstring{"Prediction, Analysis"})
\hlfunctioncall{for} (i in \hlfunctioncall{c}(1:5, 8)) \hlfunctioncall{textround}(elpos[i, ], sx[i], sy[i], lab = lab[i])
\hlfunctioncall{textround}(elpos[6, ], xx, yy * 1.5, lab = \hlfunctioncall{c}(\hlstring{"Calibration,sensitivity"}, \hlstring{"Verification,validation"}))
\hlfunctioncall{textdiamond}(elpos[7, ], sx[7], sy[7], lab = lab[7])
\hlfunctioncall{textplain}(\hlfunctioncall{c}(0.7, elpos[2, 2]), yy * 2, lab = \hlfunctioncall{c}(\hlstring{"main components"}, \hlstring{"relationships"}),
font = 3, adj = \hlfunctioncall{c}(0, 0.5))
\hlfunctioncall{textplain}(\hlfunctioncall{c}(0.7, elpos[3, 2]), yy, \hlstring{"general theory"}, adj = \hlfunctioncall{c}(0, 0.5), font = 3)
\hlfunctioncall{textplain}(\hlfunctioncall{c}(0.7, elpos[4, 2]), yy * 2, lab = \hlfunctioncall{c}(\hlstring{"literature"}, \hlstring{"measurements"}),
font = 3, adj = \hlfunctioncall{c}(0, 0.5))
\hlfunctioncall{textplain}(\hlfunctioncall{c}(0.7, elpos[6, 2]), yy * 2, lab = \hlfunctioncall{c}(\hlstring{"field data"}, \hlstring{"lab measurements"}),
font = 3, adj = \hlfunctioncall{c}(0, 0.5))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/051-flowchart-demo-flowchart1}
\begin{kframe}\begin{alltt}
\hlcomment{##### DIAGRAM}
\hlfunctioncall{par}(mar = \hlfunctioncall{c}(1, 1, 1, 1))
\hlfunctioncall{openplotmat}()
elpos <- \hlfunctioncall{coordinates}(\hlfunctioncall{c}(1, 1, 2, 4))
fromto <- \hlfunctioncall{matrix}(ncol = 2, byrow = TRUE, data = \hlfunctioncall{c}(1, 2, 2, 3, 2, 4, 4, 7, 4,
8))
nr <- \hlfunctioncall{nrow}(fromto)
arrpos <- \hlfunctioncall{matrix}(ncol = 2, nrow = nr)
\hlfunctioncall{for} (i in 1:nr) arrpos[i, ] <- \hlfunctioncall{straightarrow}(to = elpos[fromto[i, 2], ], from = elpos[fromto[i,
1], ], lwd = 2, arr.pos = 0.6, arr.length = 0.5)
\hlfunctioncall{textellipse}(elpos[1, ], 0.1, lab = \hlstring{"start"}, box.col = \hlstring{"green"}, shadow.col = \hlstring{"darkgreen"},
shadow.size = 0.005, cex = 1.5)
\hlfunctioncall{textrect}(elpos[2, ], 0.15, 0.05, lab = \hlstring{"found term?"}, box.col = \hlstring{"blue"}, shadow.col = \hlstring{"darkblue"},
shadow.size = 0.005, cex = 1.5)
\hlfunctioncall{textrect}(elpos[4, ], 0.15, 0.05, lab = \hlstring{"related?"}, box.col = \hlstring{"blue"}, shadow.col = \hlstring{"darkblue"},
shadow.size = 0.005, cex = 1.5)
\hlfunctioncall{textellipse}(elpos[3, ], 0.1, 0.1, lab = \hlfunctioncall{c}(\hlstring{"other"}, \hlstring{"term"}), box.col = \hlstring{"orange"},
shadow.col = \hlstring{"red"}, shadow.size = 0.005, cex = 1.5)
\hlfunctioncall{textellipse}(elpos[3, ], 0.1, 0.1, lab = \hlfunctioncall{c}(\hlstring{"other"}, \hlstring{"term"}), box.col = \hlstring{"orange"},
shadow.col = \hlstring{"red"}, shadow.size = 0.005, cex = 1.5)
\hlfunctioncall{textellipse}(elpos[7, ], 0.1, 0.1, lab = \hlfunctioncall{c}(\hlstring{"make"}, \hlstring{"a link"}), box.col = \hlstring{"orange"},
shadow.col = \hlstring{"red"}, shadow.size = 0.005, cex = 1.5)
\hlfunctioncall{textellipse}(elpos[8, ], 0.1, 0.1, lab = \hlfunctioncall{c}(\hlstring{"new"}, \hlstring{"article"}), box.col = \hlstring{"orange"},
shadow.col = \hlstring{"red"}, shadow.size = 0.005, cex = 1.5)
dd <- \hlfunctioncall{c}(0, 0.025)
\hlfunctioncall{text}(arrpos[2, 1] + 0.05, arrpos[2, 2], \hlstring{"yes"})
\hlfunctioncall{text}(arrpos[3, 1] - 0.05, arrpos[3, 2], \hlstring{"no"})
\hlfunctioncall{text}(arrpos[4, 1] + 0.05, arrpos[4, 2] + 0.05, \hlstring{"yes"})
\hlfunctioncall{text}(arrpos[5, 1] - 0.05, arrpos[5, 2] + 0.05, \hlstring{"no"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/051-flowchart-demo-flowchart2}
\begin{kframe}\begin{alltt}
\hlcomment{#####}
\hlfunctioncall{par}(mfrow = \hlfunctioncall{c}(2, 2))
\hlfunctioncall{par}(mar = \hlfunctioncall{c}(0, 0, 0, 0))
\hlfunctioncall{openplotmat}()
elpos <- \hlfunctioncall{coordinates}(\hlfunctioncall{c}(2, 3))
\hlfunctioncall{treearrow}(from = elpos[1:2, ], to = elpos[3:5, ], arr.side = 2, path = \hlstring{"H"})
\hlfunctioncall{for} (i in 1:5) \hlfunctioncall{textrect}(elpos[i, ], 0.15, 0.05, lab = i, cex = 1.5)
\hlfunctioncall{openplotmat}()
elpos <- \hlfunctioncall{coordinates}(\hlfunctioncall{c}(3, 2), hor = FALSE)
\hlfunctioncall{treearrow}(from = elpos[1:3, ], to = elpos[4:5, ], arr.side = 2, arr.pos = 0.2,
path = \hlstring{"V"})
\hlfunctioncall{for} (i in 1:5) \hlfunctioncall{textrect}(elpos[i, ], 0.15, 0.05, lab = i, cex = 1.5)
\hlfunctioncall{openplotmat}()
elpos <- \hlfunctioncall{coordinates}(\hlfunctioncall{c}(1, 4))
\hlfunctioncall{treearrow}(from = elpos[1, ], to = elpos[2:5, ], arr.side = 2, arr.pos = 0.7,
path = \hlstring{"H"})
\hlfunctioncall{for} (i in 1:5) \hlfunctioncall{textrect}(elpos[i, ], 0.05, 0.05, lab = i, cex = 1.5)
\hlfunctioncall{openplotmat}()
elpos <- \hlfunctioncall{coordinates}(\hlfunctioncall{c}(2, 1, 2, 3))
elpos[1, 1] <- 0.3
elpos[2, 1] <- 0.7
\hlfunctioncall{treearrow}(from = elpos[1:3, ], to = elpos[4:8, ], arr.side = 2, path = \hlstring{"H"})
\hlfunctioncall{for} (i in 1:8) \hlfunctioncall{bentarrow}(from = elpos[i, ], to = elpos[i, ] + \hlfunctioncall{c}(0.1, -0.05),
arr.pos = 1, arr.type = \hlstring{"circle"}, arr.col = \hlstring{"white"}, arr.length = 0.2)
\hlfunctioncall{for} (i in 1:8) \hlfunctioncall{textrect}(elpos[i, ], 0.05, 0.05, lab = i, cex = 1.5)
\hlfunctioncall{mtext}(side = 3, outer = TRUE, line = -2, \hlstring{"treearrow"}, cex = 1.5)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/051-flowchart-demo-flowchart3}
\begin{kframe}\begin{alltt}
\hlfunctioncall{par}(mfrow = \hlfunctioncall{c}(1, 1))
\hlfunctioncall{par}(mar = \hlfunctioncall{c}(0, 0, 0, 0))
\hlfunctioncall{openplotmat}()
elpos <- \hlfunctioncall{coordinates}(\hlfunctioncall{c}(1, 1, 2, 1))
\hlfunctioncall{straightarrow}(to = elpos[2, ], from = elpos[1, ])
\hlfunctioncall{treearrow}(from = elpos[2, ], to = elpos[3:4, ], arr.side = 2, path = \hlstring{"H"})
\hlfunctioncall{treearrow}(from = elpos[3:4, ], to = elpos[5, ], arr.side = 2, path = \hlstring{"H"})
\hlfunctioncall{segmentarrow}(from = elpos[5, ], to = elpos[2, ], dd = 0.4)
\hlfunctioncall{curvedarrow}(from = elpos[5, ], to = elpos[2, ], curve = 0.8)
col <- \hlfunctioncall{femmecol}(5)
\hlfunctioncall{texthexa}(mid = elpos[1, ], radx = 0.1, angle = 20, shadow.size = 0.01, rady = 0.05,
lab = 1, box.col = col[1])
\hlfunctioncall{textrect}(mid = elpos[2, ], radx = 0.1, shadow.size = 0.01, rady = 0.05, lab = 2,
box.col = col[2])
\hlfunctioncall{textround}(mid = elpos[3, ], radx = 0.05, shadow.size = 0.01, rady = 0.05, lab = 3,
box.col = col[3])
\hlfunctioncall{textellipse}(mid = elpos[4, ], radx = 0.05, shadow.size = 0.01, rady = 0.05,
lab = 4, box.col = col[4])
\hlfunctioncall{textellipse}(mid = elpos[5, ], radx = 0.05, shadow.size = 0.01, rady = 0.08,
angle = 45, lab = 5, box.col = col[5])
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/051-flowchart-demo-flowchart4}
\begin{kframe}\begin{alltt}
\hlfunctioncall{par}(mar = \hlfunctioncall{c}(1, 1, 1, 1))
\hlfunctioncall{openplotmat}(main = \hlstring{"Arrowtypes"})
elpos <- \hlfunctioncall{coordinates}(\hlfunctioncall{c}(1, 2, 1), mx = 0.1, my = -0.1)
\hlfunctioncall{curvedarrow}(from = elpos[1, ], to = elpos[2, ], curve = -0.5, lty = 2, lcol = 2)
\hlfunctioncall{straightarrow}(from = elpos[1, ], to = elpos[2, ], lty = 3, lcol = 3)
\hlfunctioncall{segmentarrow}(from = elpos[1, ], to = elpos[2, ], lty = 1, lcol = 1)
\hlfunctioncall{treearrow}(from = elpos[2:3, ], to = elpos[4, ], lty = 4, lcol = 4)
\hlfunctioncall{bentarrow}(from = elpos[3, ], to = elpos[3, ] - \hlfunctioncall{c}(0.1, 0.1), arr.pos = 1, lty = 5,
lcol = 5)
\hlfunctioncall{bentarrow}(from = elpos[1, ], to = elpos[3, ], lty = 5, lcol = 5)
\hlfunctioncall{selfarrow}(pos = elpos[3, ], path = \hlstring{"R"}, lty = 6, curve = 0.075, lcol = 6)
\hlfunctioncall{splitarrow}(from = elpos[1, ], to = elpos[2:3, ], lty = 1, lwd = 1, dd = 0.7,
arr.side = 1:2, lcol = 7)
\hlfunctioncall{for} (i in 1:4) \hlfunctioncall{textrect}(elpos[i, ], 0.05, 0.05, lab = i, cex = 1.5)
\hlfunctioncall{legend}(\hlstring{"topright"}, lty = 1:7, legend = \hlfunctioncall{c}(\hlstring{"segmentarrow"}, \hlstring{"curvedarrow"}, \hlstring{"straightarrow"},
\hlstring{"treearrow"}, \hlstring{"bentarrow"}, \hlstring{"selfarrow"}, \hlstring{"splitarrow"}), lwd = \hlfunctioncall{c}(\hlfunctioncall{rep}(2, 6),
1), col = 1:7)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/051-flowchart-demo-flowchart5}
\begin{kframe}\begin{alltt}
\hlfunctioncall{openplotmat}(main = \hlstring{"textbox shapes"})
rx <- 0.1
ry <- 0.05
pos <- \hlfunctioncall{coordinates}(\hlfunctioncall{c}(1, 1, 1, 1, 1, 1, 1), mx = -0.2)
\hlfunctioncall{textdiamond}(mid = pos[1, ], radx = rx, rady = ry, lab = LETTERS[1], cex = 2,
shadow.col = \hlstring{"lightblue"})
\hlfunctioncall{textellipse}(mid = pos[2, ], radx = rx, rady = ry, lab = LETTERS[2], cex = 2,
shadow.col = \hlstring{"blue"})
\hlfunctioncall{texthexa}(mid = pos[3, ], radx = rx, rady = ry, lab = LETTERS[3], cex = 2, shadow.col = \hlstring{"darkblue"})
\hlfunctioncall{textmulti}(mid = pos[4, ], nr = 7, radx = rx, rady = ry, lab = LETTERS[4], cex = 2,
shadow.col = \hlstring{"red"})
\hlfunctioncall{textrect}(mid = pos[5, ], radx = rx, rady = ry, lab = LETTERS[5], cex = 2, shadow.col = \hlstring{"darkred"})
\hlfunctioncall{textround}(mid = pos[6, ], radx = rx, rady = ry, lab = LETTERS[6], cex = 2, shadow.col = \hlstring{"black"})
\hlfunctioncall{textempty}(mid = pos[7, ], lab = LETTERS[7], cex = 2, box.col = \hlstring{"yellow"})
pos[, 1] <- pos[, 1] + 0.5
\hlfunctioncall{text}(pos[, 1], pos[, 2], \hlfunctioncall{c}(\hlstring{"textdiamond"}, \hlstring{"textellipse"}, \hlstring{"texthexa"}, \hlstring{"textmulti"},
\hlstring{"textrect"}, \hlstring{"textround"}, \hlstring{"textempty"}))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/051-flowchart-demo-flowchart6}
\begin{kframe}\begin{alltt}
mf <- \hlfunctioncall{par}(mfrow = \hlfunctioncall{c}(2, 2))
\hlfunctioncall{example}(bentarrow)
\end{alltt}
\begin{verbatim}
##
## bntrrw> openplotmat(main = "bentarrow")
##
## bntrrw> pos <- cbind( A <- seq(0.1, 0.9, by = 0.2), rev(A))
##
## bntrrw> text(pos, LETTERS[1:5], cex = 2)
##
## bntrrw> for (i in 1:4)
## bntrrw+ bentarrow(from = pos[i,] + c(0.05, 0), to = pos[i+1,] + c(0, 0.05),
## bntrrw+ arr.pos = 1, arr.adj = 1)
##
## bntrrw> for (i in 1:2)
## bntrrw+ bentarrow(from = pos[i,] + c(0.05, 0), to = pos[i+1, ] + c(0, 0.05),
## bntrrw+ arr.pos = 0.5, path = "V", lcol = "lightblue",
## bntrrw+ arr.type = "triangle")
##
## bntrrw> bentarrow(from = pos[3, ] + c(0.05, 0), to = pos[4, ] + c(0, 0.05),
## bntrrw+ arr.pos = 0.7, arr.side = 1, path = "V", lcol = "darkblue")
##
## bntrrw> bentarrow(from = pos[4, ] + c(0.05, 0), to = pos[5, ] + c(0, 0.05),
## bntrrw+ arr.pos = 0.7, arr.side = 1:2, path = "V", lcol = "blue")
\end{verbatim}
\begin{alltt}
\hlfunctioncall{example}(coordinates)
\end{alltt}
\begin{verbatim}
##
## crdnts> openplotmat(main = "coordinates")
##
## crdnts> text(coordinates(N = 6), lab = LETTERS[1:6], cex = 2)
##
## crdnts> text(coordinates(N = 8, relsize = 0.5), lab = letters[1:8], cex = 2)
##
## crdnts> openplotmat(main = "coordinates")
##
## crdnts> text(coordinates(pos = c(2, 4, 2)), lab = letters[1:8], cex = 2)
##
## crdnts> plot(0, type = "n", xlim = c(0, 5), ylim = c(2, 8), main = "coordinates")
\end{verbatim}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/051-flowchart-demo-flowchart7}
\begin{kframe}\begin{verbatim}
##
## crdnts> text(coordinates(pos = c(2, 4, 3), hor = FALSE), lab = 1:9, cex = 2)
\end{verbatim}
\begin{alltt}
\hlfunctioncall{par}(mfrow = \hlfunctioncall{c}(2, 2))
\hlfunctioncall{example}(curvedarrow)
\end{alltt}
\begin{verbatim}
##
## crvdrr> openplotmat(main = "curvedarrow")
##
## crvdrr> pos <- coordinates(pos = 4, my = 0.2)
##
## crvdrr> text(pos, LETTERS[1:4], cex = 2)
##
## crvdrr> for (i in 1:3)
## crvdrr+ curvedarrow(from = pos[1, ] + c(0,-0.05), to = pos[i+1, ] + c(0,-0.05),
## crvdrr+ curve = 0.5, arr.pos = 1)
##
## crvdrr> for (i in 1:3)
## crvdrr+ curvedarrow(from = pos[1, ] + c(0, 0.05), to = pos[i+1, ] + c(0, 0.05),
## crvdrr+ curve = -0.25, arr.adj = 1, arr.pos = 0.5,
## crvdrr+ arr.type = "triangle", arr.col = "blue")
\end{verbatim}
\begin{alltt}
\hlfunctioncall{example}(segmentarrow)
\end{alltt}
\begin{verbatim}
##
## sgmntr> openplotmat(main="segmentarrow")
##
## sgmntr> pos <-cbind(A <- seq(0.2, 0.8, by = 0.2), rev(A))
##
## sgmntr> text(pos, LETTERS[1:4], cex = 2)
##
## sgmntr> segmentarrow(from = pos[1, ] + c(0, 0.05), to = pos[2, ] + c(0, 0.05),
## sgmntr+ arr.pos = 1, arr.adj = 1, dd = 0.1,
## sgmntr+ path = "UHD", lcol = "darkred")
##
## sgmntr> segmentarrow(from = pos[2, ] + c(-0.05, 0), to = pos[3, ] + c(-0.05, 0.01),
## sgmntr+ arr.pos = 1, arr.adj = 1, dd = 0.1,
## sgmntr+ lcol = "black", arr.type = "triangle")
##
## sgmntr> segmentarrow(from = pos[2, ] + c(0.05, 0), to = pos[3, ] + c(0.05, 0.01),
## sgmntr+ arr.pos = 0.5, dd = 0.3, path = "RVL", arr.side = 1,
## sgmntr+ lcol = "lightblue", arr.type = "simple")
##
## sgmntr> segmentarrow(from = pos[3, ] + c(0.05, 0), to = pos[4, ] + c(-0.05, 0.01),
## sgmntr+ arr.pos = 0.5, dd = 0.05, path = "RVL", lcol = "darkblue",
## sgmntr+ arr.type = "ellipse")
##
## sgmntr> segmentarrow(from = pos[3, ] + c(0, -0.05), to = pos[4, ] + c(0, 0.05),
## sgmntr+ arr.pos = 0.5, arr.side = 3, dd = 0.05, path = "DHU",
## sgmntr+ lcol = "darkgreen")
##
## sgmntr> segmentarrow(from = pos[3,] + c(-0.05, -0.05), to = pos[4, ] + c(0, -0.05),
## sgmntr+ arr.pos = 0.5, arr.side = 1:3, dd = 0.3, path = "DHU",
## sgmntr+ lcol = "green")
\end{verbatim}
\begin{alltt}
\hlfunctioncall{example}(selfarrow)
\end{alltt}
\begin{verbatim}
##
## slfrrw> openplotmat(main = "selfarrow")
##
## slfrrw> pos <- coordinates(3, mx = 0.05)
##
## slfrrw> text(pos, LETTERS[1:3], cex = 2)
##
## slfrrw> for (i in 1:3)
## slfrrw+ selfarrow(pos = pos[i, ], path = "R", arr.pos = 0.2,
## slfrrw+ curve = c(0.05, 0.1), lcol = "darkred")
##
## slfrrw> for (i in 1:3)
## slfrrw+ selfarrow(pos = pos[i, ], path = "L", arr.pos = 0.7,
## slfrrw+ lcol = "darkblue", curve = c(0.05, 0.05))
##
## slfrrw> for (i in 1:3)
## slfrrw+ selfarrow(pos = pos[i, ], path = "L", arr.pos = 0.5,
## slfrrw+ lcol = "darkgreen", code = i, arr.type = "triangle")
\end{verbatim}
\begin{alltt}
\hlfunctioncall{example}(straightarrow)
\end{alltt}
\begin{verbatim}
##
## strght> openplotmat(main = "straightarrow")
\end{verbatim}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/051-flowchart-demo-flowchart8}
\begin{kframe}\begin{verbatim}
##
## strght> pos <- coordinates(c(2, 3, 1))
##
## strght> for (i in 1:5)
## strght+ straightarrow(from = pos[i, ], to = pos[i+1, ], arr.pos = 0.5)
##
## strght> straightarrow(from = pos[6, ], to = pos[6, ] + c(0.3, 0.),
## strght+ arr.type = "T", arr.pos = 1, arr.lwd = 3)
##
## strght> for (i in 1:6)
## strght+ textrect(pos[i, ], lab = LETTERS[i], radx = 0.05)
\end{verbatim}
\begin{alltt}
\hlfunctioncall{par}(mfrow = \hlfunctioncall{c}(2, 2))
\hlfunctioncall{example}(treearrow)
\end{alltt}
\begin{verbatim}
##
## trerrw> openplotmat(main = "treearrow")
##
## trerrw> pos <- coordinates(c(3, 2, 4, 1))
##
## trerrw> treearrow(from = pos[1:5, ], to = pos[6:10, ])
##
## trerrw> for (i in 1:10)
## trerrw+ textrect(pos[i, ], lab = i, cex = 2, radx = 0.05)
##
## trerrw> openplotmat(main = "treearrow")
##
## trerrw> pos <- coordinates(c(2, 4), hor = FALSE)
##
## trerrw> treearrow(from = pos[1:2, ], to = pos[3:6, ],
## trerrw+ arr.side = 1:2, path = "V")
##
## trerrw> for (i in 1:6)
## trerrw+ textrect(pos[i, ], lab = i, cex = 2, radx = 0.05)
##
## trerrw> openplotmat(main = "treearrow")
##
## trerrw> pos <- coordinates(c(3, 5, 7, 7, 5, 3))
##
## trerrw> treearrow(from = pos[1:15, ], to = pos[15:30, ], arr.side = 0)
##
## trerrw> for (i in 1:30)
## trerrw+ textrect(pos[i, ], lab = i, cex = 1.2, radx = 0.025)
\end{verbatim}
\begin{alltt}
\hlfunctioncall{par}(mfrow = \hlfunctioncall{c}(2, 2))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/051-flowchart-demo-flowchart9}
\begin{kframe}\begin{alltt}
\hlfunctioncall{example}(splitarrow)
\end{alltt}
\begin{verbatim}
##
## spltrr> openplotmat(main = "splitarrow")
##
## spltrr> pos <- coordinates(c(1, 2, 2, 4, 1))
##
## spltrr> splitarrow(from = pos[1, ], to = pos[2:10, ],
## spltrr+ arr.side = 1, centre = c(0.5, 0.625))
##
## spltrr> for (i in 1:10)
## spltrr+ textrect(pos[i, ], lab = i, cex = 2, radx = 0.05)
##
## spltrr> openplotmat(main = "splitarrow")
##
## spltrr> pos <- coordinates(c(1, 3))
##
## spltrr> splitarrow(from = pos[1,], to = pos[2:4, ], arr.side = 1)
##
## spltrr> splitarrow(from = pos[1,], to = pos[2:4, ], arr.side = 2)
##
## spltrr> for (i in 1:4)
## spltrr+ textrect(pos[i, ], lab = i, cex = 2, radx = 0.05)
##
## spltrr> openplotmat(main = "splitarrow")
##
## spltrr> pos <- coordinates(N = 6)
##
## spltrr> pos <- rbind(c(0.5, 0.5), pos)
##
## spltrr> splitarrow(from = pos[1, ], to = pos[2:7, ], arr.side = 2)
##
## spltrr> for (i in 1:7)
## spltrr+ textrect(pos[i, ], lab = i, cex = 2, radx = 0.05)
\end{verbatim}
\begin{alltt}
\hlfunctioncall{par}(mfrow = \hlfunctioncall{c}(2, 2))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/051-flowchart-demo-flowchart10}
\begin{kframe}\begin{alltt}
\hlfunctioncall{example}(textdiamond)
\end{alltt}
\begin{verbatim}
##
## txtdmn> openplotmat(xlim = c(-0.1, 1.1), main = "textdiamond")
##
## txtdmn> for (i in 1:10)
## txtdmn+ textdiamond(mid = runif(2), col = i, radx = 0.1, rady = 0.05,
## txtdmn+ lab = LETTERS[i], cex = 2, angle = runif(1)*360)
\end{verbatim}
\begin{alltt}
\hlfunctioncall{example}(textellipse)
\end{alltt}
\begin{verbatim}
##
## txtllp> openplotmat(xlim = c(-0.1, 1.1), main = "textellipse")
##
## txtllp> for (i in 1:10)
## txtllp+ textellipse(mid = runif(2), col = i, box.col = grey(0.95),
## txtllp+ radx = 0.1, rady = 0.05, lab = LETTERS[i],
## txtllp+ cex = 2, angle = runif(1)*360)
\end{verbatim}
\begin{alltt}
\hlfunctioncall{example}(textempty)
\end{alltt}
\begin{verbatim}
##
## txtmpt> openplotmat(xlim = c(-0.1, 1.1), col = "lightgrey", main = "textempty")
##
## txtmpt> for (i in 1:10)
## txtmpt+ textempty(mid = runif(2), box.col = i, lab = LETTERS[i], cex = 2)
##
## txtmpt> textempty(mid = c(0.5, 0.5), adj = c(0, 0),
## txtmpt+ lab = "textempty", box.col = "white")
\end{verbatim}
\begin{alltt}
\hlfunctioncall{example}(texthexa)
\end{alltt}
\begin{verbatim}
##
## texthx> openplotmat(xlim = c(-0.1, 1.1), main = "texthexa")
\end{verbatim}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/051-flowchart-demo-flowchart11}
\begin{kframe}\begin{verbatim}
##
## texthx> for (i in 1:20)
## texthx+ texthexa(mid = runif(2), angle = runif(1)*360, col = i,
## texthx+ box.col = grey(0.95), radx = 0.1, rady = 0.05,
## texthx+ lab = LETTERS[i], cex = 2)
\end{verbatim}
\begin{alltt}
\hlfunctioncall{example}(textmulti)
\end{alltt}
\begin{verbatim}
##
## txtmlt> openplotmat(xlim = c(-0.1, 1.1), main = "textmulti")
##
## txtmlt> for (i in 1:10)
## txtmlt+ textmulti(mid = runif(2), col = i, radx = 0.1, rady = 0.1,
## txtmlt+ lab = LETTERS[i], cex = 2, nr = trunc(i/1.5)+3)
\end{verbatim}
\begin{alltt}
\hlfunctioncall{example}(textplain)
\end{alltt}
\begin{verbatim}
##
## txtpln> openplotmat(main = "textplain")
##
## txtpln> textplain(mid = c(0.5, 0.5),
## txtpln+ lab = c("this text is", "centered", "4 strings", "on 4 lines"))
##
## txtpln> textplain(mid = c(0.5, 0.2), adj = c(0, 0.5), font = 2, height = 0.05,
## txtpln+ lab = c("this text is","left alligned"))
##
## txtpln> textplain(mid = c(0.5, 0.8), adj = c(1, 0.5), font = 3, height = 0.05,
## txtpln+ lab = c("this text is","right alligned"))
\end{verbatim}
\begin{alltt}
\hlfunctioncall{example}(textrect)
\end{alltt}
\begin{verbatim}
##
## txtrct> openplotmat(xlim = c(-0.1, 1.1), main = "textrect")
##
## txtrct> for (i in 1:10)
## txtrct+ textrect(mid = runif(2), col = i, radx = 0.1, rady = 0.1,
## txtrct+ lab = LETTERS[i], cex = 2)
##
## txtrct> openplotmat(xlim = c(-0.1, 1.1), main = "textparallel")
\end{verbatim}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/051-flowchart-demo-flowchart12}
\begin{kframe}\begin{verbatim}
##
## txtrct> elpos <-coordinates (c(1, 1, 1, 1, 1))
##
## txtrct> textparallel(mid = elpos[1,], col = 1, radx = 0.2, rady = 0.1,
## txtrct+ lab = "theta=20", theta = 20)
##
## txtrct> textparallel(mid = elpos[2,], col = 1, radx = 0.2, rady = 0.1,
## txtrct+ lab = "theta=60", theta = 60)
##
## txtrct> textparallel(mid = elpos[3,], col = 1, radx = 0.2, rady = 0.1,
## txtrct+ lab = "theta=100", theta = 100)
##
## txtrct> textparallel(mid = elpos[4,], col = 1, radx = 0.2, rady = 0.1,
## txtrct+ lab = "theta=140", theta = 140)
##
## txtrct> textparallel(mid = elpos[5,], col = 1, radx = 0.2, rady = 0.1,
## txtrct+ lab = "theta=170", theta = 170)
\end{verbatim}
\begin{alltt}
\hlfunctioncall{example}(textround)
\end{alltt}
\begin{verbatim}
##
## txtrnd> openplotmat(xlim = c(-0.1, 1.1), main = "textround")
##
## txtrnd> for (i in 1:10)
## txtrnd+ textround(mid = runif(2), col = i,
## txtrnd+ radx = 0.03, rady = 0.075,
## txtrnd+ lab = LETTERS[i], cex = 2)
\end{verbatim}
\begin{alltt}
\hlfunctioncall{par}(mfrow = mf)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/051-flowchart-demo-flowchart13}
\end{knitrout}
\end{document}

Suppress super long output

First we redefine the output hook:

# the default output hook
hook_output = knit_hooks$get("output")
knit_hooks$set(output = function(x, options) {
    if (!is.null(n <- options$out.lines)) {
        x = unlist(stringr::str_split(x, "\n"))
        if (length(x) > n) {
            # truncate the output
            x = c(head(x, n), "....\n")
        }
        x = paste(x, collapse = "\n")  # paste first n lines together
    }
    hook_output(x, options)
})

And we do not want the output to be more than 4 lines, so we set this option globally:

opts_chunk$set(out.lines = 4)

Test the new output hook:

1 + 1  # this is short
## [1] 2

The output of this chunk is truncated:

1:100
##   [1]   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17
##  [18]  18  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34
##  [35]  35  36  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51
##  [52]  52  53  54  55  56  57  58  59  60  61  62  63  64  65  66  67  68
....
# Suppress super long output
First we redefine the output hook:
```{r setup}
# the default output hook
hook_output = knit_hooks$get('output')
knit_hooks$set(output = function(x, options) {
if (!is.null(n <- options$out.lines)) {
x = unlist(stringr::str_split(x, '\n'))
if (length(x) > n) {
# truncate the output
x = c(head(x, n), '....\n')
}
x = paste(x, collapse = '\n') # paste first n lines together
}
hook_output(x, options)
})
```
And we do not want the output to be more than 4 lines, so we set this option globally:
```{r}
opts_chunk$set(out.lines = 4)
```
Test the new output hook:
```{r test-a}
1+1 # this is short
```
The output of this chunk is truncated:
```{r test-b}
1:100
```
\documentclass{beamer}
\begin{document}
<<setup, include=FALSE>>=
# smaller font size for chunks
opts_chunk$set(size = 'footnotesize')
hook_plot = knit_hooks$get('plot') # the default hook
# tweak and reset the default hook
knit_hooks$set(plot = function(x, options) {
txt = hook_plot(x, options)
if (options$fig.cur <= 0) return(txt)
# add \only<n> before \includegraphics
gsub('(\\\\includegraphics[^}]+})', sprintf('\\\\only<%d>{\\1}', options$fig.cur), txt)
})
@
\title{Show Plots Step by Step with knitr in Beamer}
\author{Yihui Xie}
\maketitle
\begin{frame}
The question came from \url{http://r.789695.n4.nabble.com/plots-for-presentation-td4645869.html}
\end{frame}
% very important to use option [fragile] for frames containing code output!
\begin{frame}[fragile]
We will add ``\textbackslash{}only'' to the plots so they show up one by one.
<<boring-plots, out.width='.5\\linewidth', fig.show='hold', fig.keep='all', fig.align='center'>>=
par(mar = c(4, 4, .1, .1))
x = rnorm(100)
hist(x, main='')
rug(x)
abline(v = mean(x), lty = 2, lwd = 3)
@
\end{frame}
\end{document}
\documentclass{beamer}\usepackage[]{graphicx}\usepackage[]{color}
%% maxwidth is the original width if it is less than linewidth
%% otherwise use linewidth (to make sure the graphics do not exceed the margin)
\makeatletter
\def\maxwidth{ %
\ifdim\Gin@nat@width>\linewidth
\linewidth
\else
\Gin@nat@width
\fi
}
\makeatother
\definecolor{fgcolor}{rgb}{0.2, 0.2, 0.2}
\newcommand{\hlnumber}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlfunctioncall}[1]{\textcolor[rgb]{0.501960784313725,0,0.329411764705882}{\textbf{#1}}}%
\newcommand{\hlstring}[1]{\textcolor[rgb]{0.6,0.6,1}{#1}}%
\newcommand{\hlkeyword}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlargument}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlcomment}[1]{\textcolor[rgb]{0.180392156862745,0.6,0.341176470588235}{#1}}%
\newcommand{\hlroxygencomment}[1]{\textcolor[rgb]{0.43921568627451,0.47843137254902,0.701960784313725}{#1}}%
\newcommand{\hlformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hleqformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlassignement}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlpackage}[1]{\textcolor[rgb]{0.588235294117647,0.709803921568627,0.145098039215686}{#1}}%
\newcommand{\hlslot}[1]{\textit{#1}}%
\newcommand{\hlsymbol}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlprompt}[1]{\textcolor[rgb]{0.2,0.2,0.2}{#1}}%
\usepackage{framed}
\makeatletter
\newenvironment{kframe}{%
\def\at@end@of@kframe{}%
\ifinner\ifhmode%
\def\at@end@of@kframe{\end{minipage}}%
\begin{minipage}{\columnwidth}%
\fi\fi%
\def\FrameCommand##1{\hskip\@totalleftmargin \hskip-\fboxsep
\colorbox{shadecolor}{##1}\hskip-\fboxsep
% There is no \\@totalrightmargin, so:
\hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth}%
\MakeFramed {\advance\hsize-\width
\@totalleftmargin\z@ \linewidth\hsize
\@setminipage}}%
{\par\unskip\endMakeFramed%
\at@end@of@kframe}
\makeatother
\definecolor{shadecolor}{rgb}{.97, .97, .97}
\definecolor{messagecolor}{rgb}{0, 0, 0}
\definecolor{warningcolor}{rgb}{1, 0, 1}
\definecolor{errorcolor}{rgb}{1, 0, 0}
\newenvironment{knitrout}{}{} % an empty environment to be redefined in TeX
\usepackage{alltt}
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
\begin{document}
\title{Show Plots Step by Step with knitr in Beamer}
\author{Yihui Xie}
\maketitle
\begin{frame}
The question came from \url{http://r.789695.n4.nabble.com/plots-for-presentation-td4645869.html}
\end{frame}
% very important to use option [fragile] for frames containing code output!
\begin{frame}[fragile]
We will add ``\textbackslash{}only'' to the plots so they show up one by one.
\begin{knitrout}\footnotesize
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlfunctioncall{par}(mar = \hlfunctioncall{c}(4, 4, 0.1, 0.1))
x = \hlfunctioncall{rnorm}(100)
\hlfunctioncall{hist}(x, main = \hlstring{""})
\hlfunctioncall{rug}(x)
\hlfunctioncall{abline}(v = \hlfunctioncall{mean}(x), lty = 2, lwd = 3)
\end{alltt}
\end{kframe}
{\centering \only<1>{\includegraphics[width=.5\linewidth]{figure/053-beamer-only-boring-plots1}}
\only<2>{\includegraphics[width=.5\linewidth]{figure/053-beamer-only-boring-plots2}}
\only<3>{\includegraphics[width=.5\linewidth]{figure/053-beamer-only-boring-plots3}}
}
\end{knitrout}
\end{frame}
\end{document}

We can draw plots in a loop.

for (i in 1:5) {
    cat("\n\nthis is plot ", i, "\n\n")
    plot(1:i)
}

this is plot 1

this is plot 2

this is plot 3

this is plot 4

this is plot 5

We can draw plots in a loop.
```{r loop, results='asis', fig.cap=rep('',5)}
for (i in 1:5) {
cat('\n\nthis is plot ', i, '\n\n')
plot(1:i)
}
```
\documentclass{article}
\usepackage{multicol}
\title{Using knitr with multicols}
\author{Yihui Xie}
\begin{document}
\maketitle
Here is a paragraph outside the multicols environment. Here is a paragraph outside the multicols environment.
\begin{multicols}{2}
Here is a paragraph inside the multicols environment. Here is a paragraph inside the multicols environment.
<<test>>=
1+1
2*pi*10
par(mar=c(4, 4, .1, .1))
plot(rnorm(100))
@
and follow that up with some random text.
\end{multicols}
\end{document}
\documentclass{article}\usepackage[]{graphicx}\usepackage[]{color}
%% maxwidth is the original width if it is less than linewidth
%% otherwise use linewidth (to make sure the graphics do not exceed the margin)
\makeatletter
\def\maxwidth{ %
\ifdim\Gin@nat@width>\linewidth
\linewidth
\else
\Gin@nat@width
\fi
}
\makeatother
\definecolor{fgcolor}{rgb}{0.2, 0.2, 0.2}
\newcommand{\hlnumber}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlfunctioncall}[1]{\textcolor[rgb]{0.501960784313725,0,0.329411764705882}{\textbf{#1}}}%
\newcommand{\hlstring}[1]{\textcolor[rgb]{0.6,0.6,1}{#1}}%
\newcommand{\hlkeyword}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlargument}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlcomment}[1]{\textcolor[rgb]{0.180392156862745,0.6,0.341176470588235}{#1}}%
\newcommand{\hlroxygencomment}[1]{\textcolor[rgb]{0.43921568627451,0.47843137254902,0.701960784313725}{#1}}%
\newcommand{\hlformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hleqformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlassignement}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlpackage}[1]{\textcolor[rgb]{0.588235294117647,0.709803921568627,0.145098039215686}{#1}}%
\newcommand{\hlslot}[1]{\textit{#1}}%
\newcommand{\hlsymbol}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlprompt}[1]{\textcolor[rgb]{0.2,0.2,0.2}{#1}}%
\usepackage{framed}
\makeatletter
\newenvironment{kframe}{%
\def\at@end@of@kframe{}%
\ifinner\ifhmode%
\def\at@end@of@kframe{\end{minipage}}%
\begin{minipage}{\columnwidth}%
\fi\fi%
\def\FrameCommand##1{\hskip\@totalleftmargin \hskip-\fboxsep
\colorbox{shadecolor}{##1}\hskip-\fboxsep
% There is no \\@totalrightmargin, so:
\hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth}%
\MakeFramed {\advance\hsize-\width
\@totalleftmargin\z@ \linewidth\hsize
\@setminipage}}%
{\par\unskip\endMakeFramed%
\at@end@of@kframe}
\makeatother
\definecolor{shadecolor}{rgb}{.97, .97, .97}
\definecolor{messagecolor}{rgb}{0, 0, 0}
\definecolor{warningcolor}{rgb}{1, 0, 1}
\definecolor{errorcolor}{rgb}{1, 0, 0}
\newenvironment{knitrout}{}{} % an empty environment to be redefined in TeX
\usepackage{alltt}
\usepackage{multicol}
\title{Using knitr with multicols}
\author{Yihui Xie}
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
\begin{document}
\maketitle
Here is a paragraph outside the multicols environment. Here is a paragraph outside the multicols environment.
\begin{multicols}{2}
Here is a paragraph inside the multicols environment. Here is a paragraph inside the multicols environment.
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
1 + 1
\end{alltt}
\begin{verbatim}
## [1] 2
\end{verbatim}
\begin{alltt}
2 * pi * 10
\end{alltt}
\begin{verbatim}
## [1] 62.83
\end{verbatim}
\begin{alltt}
\hlfunctioncall{par}(mar = \hlfunctioncall{c}(4, 4, 0.1, 0.1))
\hlfunctioncall{plot}(\hlfunctioncall{rnorm}(100))
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/055-multicols-test}
\end{knitrout}
and follow that up with some random text.
\end{multicols}
\end{document}

A huge plot (scatter plot matrix)

One disadvantage of recordPlot() is that it may not be able to record huge plots due to memory limits, e.g. a scatter plot matrix of tens of thousands of points:

# generate some random data
dat = matrix(runif(1e+05), ncol = 5)
dat[, 3] = -0.2 * dat[, 1] + 0.8 * dat[, 2]  # to make the plot less boring
pairs(dat)

But scatter plots with such a large number of points are usually difficult to read (basically you can see nothing), so we'd better use some alternative ways to visualize them. For example, we can use 2D density estimates and draw contour plots, or just plot the LOWESS curve.

dens2d = function(x, y, ...) {
    library(MASS)
    res = kde2d(x, y)
    with(res, contour(x, y, z, add = TRUE))
}
pairs(dat, lower.panel = dens2d, upper.panel = function(x, y, ...) {
    lines(lowess(y ~ x), col = "red")
})

plot of chunk line-contour

# A huge plot (scatter plot matrix)
One disadvantage of `recordPlot()` is that it may not be able to record huge plots due to memory limits, e.g. a scatter plot matrix of tens of thousands of points:
```{r gen-data, cache=TRUE}
# generate some random data
dat = matrix(runif(100000), ncol=5)
dat[, 3] = -.2 * dat[, 1] + .8 * dat[, 2] # to make the plot less boring
```{r eval=FALSE}
pairs(dat)
```
But scatter plots with such a large number of points are usually difficult to read (basically you can see nothing), so we'd better use some alternative ways to visualize them. For example, we can use 2D density estimates and draw contour plots, or just plot the LOWESS curve.
```{r line-contour, cache=TRUE, dependson='gen-data'}
dens2d = function(x, y, ...) {
library(MASS)
res = kde2d(x, y)
with(res, contour(x, y, z, add = TRUE))
}
pairs(dat, lower.panel = dens2d, upper.panel = function(x, y, ...) {
lines(lowess(y ~ x), col = 'red')
})
```

A dot example

A dot-example taken from the man-pages. You need to install the graphviz package.

digraph test123 {
  a -> b -> c;
  a -> {x y};
  b [shape=box];
  c [label="hello\nworld",color=blue,fontsize=24,
      fontname="Palatino-Italic",fontcolor=red,style=filled];
  a -> z [label="hi", weight=100];
  x -> z [label="multi-line\nlabel"];
  edge [style=dashed,color=red];
  b -> x;
  {rank=same; b x}
}

Funky dot

# A dot example
A `dot`-example taken from the man-pages. You need to install the `graphviz` package.
```{r dot-ex, engine = "dot", fig.cap = "Funky dot"}
digraph test123 {
a -> b -> c;
a -> {x y};
b [shape=box];
c [label="hello\nworld",color=blue,fontsize=24,
fontname="Palatino-Italic",fontcolor=red,style=filled];
a -> z [label="hi", weight=100];
x -> z [label="multi-line\nlabel"];
edge [style=dashed,color=red];
b -> x;
{rank=same; b x}
}
```

TikZ graphics

Description

The engine inserts the code into a latex-string-template, which is then processed by LaTeX (and ImageMagick convert if fig.ext is not pdf).

Options

You can pass some options to the engine by defining engine.opts, e.g. use your own template instead of the default one to include the tikz code: engine.opts = list(template = "mytemplate.tex"). The default template can be found under system.file('misc', 'tikz2pdf.tex', package = 'knitr').

Example

An example of the tikz-engine from https://raw.github.com/sdiehl/cats/master/misc/example.md

\usetikzlibrary{arrows}
\begin{tikzpicture}[node distance=2cm, auto,>=latex', thick, scale = 0.5]
\node (P) {$P$};
\node (B) [right of=P] {$B$};
\node (A) [below of=P] {$A$};
\node (C) [below of=B] {$C$};
\node (P1) [node distance=1.4cm, left of=P, above of=P] {$\hat{P}$};
\draw[->] (P) to node {$f$} (B);
\draw[->] (P) to node [swap] {$g$} (A);
\draw[->] (A) to node [swap] {$f$} (C);
\draw[->] (B) to node {$g$} (C);
\draw[->, bend right] (P1) to node [swap] {$\hat{g}$} (A);
\draw[->, bend left] (P1) to node {$\hat{f}$} (B);
\draw[->, dashed] (P1) to node {$k$} (P);
\end{tikzpicture}

Funky tikz

Tips

To develop the tikz-code, you could use qtikz or ktikz.

# TikZ graphics
## Description
The engine inserts the code into a latex-string-template, which is then processed by LaTeX (and ImageMagick `convert` if `fig.ext` is not `pdf`).
## Options
You can pass some options to the engine by defining `engine.opts`, e.g. use your own template instead of the default one to include the tikz code: `engine.opts = list(template = "mytemplate.tex")`. The default template can be found under `system.file('misc', 'tikz2pdf.tex', package = 'knitr')`.
## Example
An example of the tikz-engine from <https://raw.github.com/sdiehl/cats/master/misc/example.md>
```{r tikz-ex, engine = "tikz", fig.cap = "Funky tikz", fig.ext = 'png', cache=TRUE}
\usetikzlibrary{arrows}
\begin{tikzpicture}[node distance=2cm, auto,>=latex', thick, scale = 0.5]
\node (P) {$P$};
\node (B) [right of=P] {$B$};
\node (A) [below of=P] {$A$};
\node (C) [below of=B] {$C$};
\node (P1) [node distance=1.4cm, left of=P, above of=P] {$\hat{P}$};
\draw[->] (P) to node {$f$} (B);
\draw[->] (P) to node [swap] {$g$} (A);
\draw[->] (A) to node [swap] {$f$} (C);
\draw[->] (B) to node {$g$} (C);
\draw[->, bend right] (P1) to node [swap] {$\hat{g}$} (A);
\draw[->, bend left] (P1) to node {$\hat{f}$} (B);
\draw[->, dashed] (P1) to node {$k$} (P);
\end{tikzpicture}
```
## Tips
To develop the tikz-code, you could use `qtikz` or `ktikz`.
\documentclass{article}
% \usepackage{lmodern} % use latin modern roman
\title{The tikz Device}
\author{Yihui Xie}
\begin{document}
\maketitle
<<setup, include=FALSE>>=
options(width = 40)
@
First you need to install the tikzDevice package, e.g.
<<install-tikz, eval=FALSE>>=
install.packages("tikzDevice", repos="http://R-Forge.R-project.org")
@
Then just specify \texttt{dev='tikz'} in the chunk header, and you are done.
<<tikz-ex, dev='tikz', fig.width=4, fig.height=4, cache=TRUE>>=
plot(1, xlab = '$x_i$', ylab = '$y_i$', main = "Isn't \\LaTeX{} Awesome?")
text(1, 1, 'The font style is consistent\n\n with your document')
@
\end{document}
\documentclass{article}\usepackage[]{graphicx}\usepackage[]{color}
%% maxwidth is the original width if it is less than linewidth
%% otherwise use linewidth (to make sure the graphics do not exceed the margin)
\makeatletter
\def\maxwidth{ %
\ifdim\Gin@nat@width>\linewidth
\linewidth
\else
\Gin@nat@width
\fi
}
\makeatother
\definecolor{fgcolor}{rgb}{0.2, 0.2, 0.2}
\newcommand{\hlnumber}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlfunctioncall}[1]{\textcolor[rgb]{0.501960784313725,0,0.329411764705882}{\textbf{#1}}}%
\newcommand{\hlstring}[1]{\textcolor[rgb]{0.6,0.6,1}{#1}}%
\newcommand{\hlkeyword}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlargument}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlcomment}[1]{\textcolor[rgb]{0.180392156862745,0.6,0.341176470588235}{#1}}%
\newcommand{\hlroxygencomment}[1]{\textcolor[rgb]{0.43921568627451,0.47843137254902,0.701960784313725}{#1}}%
\newcommand{\hlformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hleqformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlassignement}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlpackage}[1]{\textcolor[rgb]{0.588235294117647,0.709803921568627,0.145098039215686}{#1}}%
\newcommand{\hlslot}[1]{\textit{#1}}%
\newcommand{\hlsymbol}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlprompt}[1]{\textcolor[rgb]{0.2,0.2,0.2}{#1}}%
\usepackage{framed}
\makeatletter
\newenvironment{kframe}{%
\def\at@end@of@kframe{}%
\ifinner\ifhmode%
\def\at@end@of@kframe{\end{minipage}}%
\begin{minipage}{\columnwidth}%
\fi\fi%
\def\FrameCommand##1{\hskip\@totalleftmargin \hskip-\fboxsep
\colorbox{shadecolor}{##1}\hskip-\fboxsep
% There is no \\@totalrightmargin, so:
\hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth}%
\MakeFramed {\advance\hsize-\width
\@totalleftmargin\z@ \linewidth\hsize
\@setminipage}}%
{\par\unskip\endMakeFramed%
\at@end@of@kframe}
\makeatother
\definecolor{shadecolor}{rgb}{.97, .97, .97}
\definecolor{messagecolor}{rgb}{0, 0, 0}
\definecolor{warningcolor}{rgb}{1, 0, 1}
\definecolor{errorcolor}{rgb}{1, 0, 0}
\newenvironment{knitrout}{}{} % an empty environment to be redefined in TeX
\usepackage{alltt}
% \usepackage{lmodern} % use latin modern roman
\title{The tikz Device}
\author{Yihui Xie}
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
\begin{document}
\maketitle
First you need to install the tikzDevice package, e.g.
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlfunctioncall{install.packages}(\hlstring{"tikzDevice"}, repos = \hlstring{"http://R-Forge.R-project.org"})
\end{alltt}
\end{kframe}
\end{knitrout}
Then just specify \texttt{dev='tikz'} in the chunk header, and you are done.
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlfunctioncall{plot}(1, xlab = \hlstring{"$x_i$"}, ylab = \hlstring{"$y_i$"}, main = \hlstring{"Isn't \textbackslash{}\textbackslash{}LaTeX\{\} Awesome?"})
\hlfunctioncall{text}(1, 1, \hlstring{"The font style is consistent\textbackslash{}n\textbackslash{}n with your document"})
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/059-tikz-tikz-ex}
\end{knitrout}
\end{document}

SAS

As long as SAS is not in your PATH variable, you need to specify its full path with the engine.path option, e.g.

data _null_;
put 'Hello, world!';
run;

I do not have SAS installed on my system so I did not really run the code above (eval=FALSE).

I'm not familiar with SAS either; please feel free to improve the sas engine in knitr.

# SAS
As long as SAS is not in your `PATH` variable, you need to specify its full path with the `engine.path` option, e.g.
```{r hello-world, engine='sas', engine.path='C:\\Program Files\\SASHome\\x86\\SASFoundation\\9.3\\sas.exe', eval=FALSE}
data _null_;
put 'Hello, world!';
run;
```
I do not have SAS installed on my system so I did not really run the code above (`eval=FALSE`).
I'm not familiar with SAS either; please feel free to improve the [`sas` engine](https://github.com/yihui/knitr/blob/master/R/engine.R) in **knitr**.

Pass variables to bash scripts

Use Sys.setenv():

Sys.setenv(EXAMPLES = "example/path")

Now we write a bash code chunk:

echo $EXAMPLES
## example/path

It works.

# Pass variables to bash scripts
Use `Sys.setenv()`:
```{r}
Sys.setenv(EXAMPLES = 'example/path')
```
Now we write a `bash` code chunk:
```{r engine='bash'}
echo $EXAMPLES
```
It works.

Write the chunk wrapper to the output

All chunk options are stored in options$params.src.

knit_hooks$set(wrapper = function(before, options, envir) {
    if (before) {
        sprintf("    ```{r %s}\n", options$params.src)
    } else "    ```\n"
})

Can I write the three backticks in the output?

```{r test_label, wrapper=TRUE, eval=FALSE}
1 + 1
plot(1)
```

By default the chunk wrapper will not show up, e.g.

rnorm(100)
y ~ x
# Write the chunk wrapper to the output
All chunk options are stored in `options$params.src`.
```{r setup}
knit_hooks$set(wrapper = function(before, options, envir) {
if (before) {
sprintf(' ```{r %s}\n', options$params.src)
} else ' ```\n'
})
```
Can I write the three backticks in the output?
```{r test_label, wrapper=TRUE, eval=FALSE}
1+1
plot(1)
```
By default the chunk wrapper will not show up, e.g.
```{r test2, eval=FALSE}
rnorm(100)
y~x
```
\documentclass{article}
\usepackage{url}
\begin{document}
<<setup>>=
knit_hooks$set(wrapper = function(before, options, envir) {
sprintf('\\begin{alltt}%s\n\\end{alltt}',
if (before) sprintf('<<%s>>=', options$params.src) else '@')
})
@
I want to display \verb|<<>>=| in the output since I'm writing a tutorial:
<<test_label, wrapper=TRUE, eval=FALSE>>=
1+1
plot(1)
@
Another approach was mentioned in FAQ 9 (\url{https://github.com/yihui/knitr/blob/master/FAQ.md}), i.e. destroy the chunk header. Here is an example:
\begin{verbatim}
\Sexpr{''}<<test_label, echo=1:2>>=
1 + 1
rnorm(10)
2 + 2
@
\end{verbatim}
\end{document}
\documentclass{article}\usepackage[]{graphicx}\usepackage[]{color}
%% maxwidth is the original width if it is less than linewidth
%% otherwise use linewidth (to make sure the graphics do not exceed the margin)
\makeatletter
\def\maxwidth{ %
\ifdim\Gin@nat@width>\linewidth
\linewidth
\else
\Gin@nat@width
\fi
}
\makeatother
\definecolor{fgcolor}{rgb}{0.2, 0.2, 0.2}
\newcommand{\hlnumber}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlfunctioncall}[1]{\textcolor[rgb]{0.501960784313725,0,0.329411764705882}{\textbf{#1}}}%
\newcommand{\hlstring}[1]{\textcolor[rgb]{0.6,0.6,1}{#1}}%
\newcommand{\hlkeyword}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlargument}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlcomment}[1]{\textcolor[rgb]{0.180392156862745,0.6,0.341176470588235}{#1}}%
\newcommand{\hlroxygencomment}[1]{\textcolor[rgb]{0.43921568627451,0.47843137254902,0.701960784313725}{#1}}%
\newcommand{\hlformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hleqformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlassignement}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlpackage}[1]{\textcolor[rgb]{0.588235294117647,0.709803921568627,0.145098039215686}{#1}}%
\newcommand{\hlslot}[1]{\textit{#1}}%
\newcommand{\hlsymbol}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlprompt}[1]{\textcolor[rgb]{0.2,0.2,0.2}{#1}}%
\usepackage{framed}
\makeatletter
\newenvironment{kframe}{%
\def\at@end@of@kframe{}%
\ifinner\ifhmode%
\def\at@end@of@kframe{\end{minipage}}%
\begin{minipage}{\columnwidth}%
\fi\fi%
\def\FrameCommand##1{\hskip\@totalleftmargin \hskip-\fboxsep
\colorbox{shadecolor}{##1}\hskip-\fboxsep
% There is no \\@totalrightmargin, so:
\hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth}%
\MakeFramed {\advance\hsize-\width
\@totalleftmargin\z@ \linewidth\hsize
\@setminipage}}%
{\par\unskip\endMakeFramed%
\at@end@of@kframe}
\makeatother
\definecolor{shadecolor}{rgb}{.97, .97, .97}
\definecolor{messagecolor}{rgb}{0, 0, 0}
\definecolor{warningcolor}{rgb}{1, 0, 1}
\definecolor{errorcolor}{rgb}{1, 0, 0}
\newenvironment{knitrout}{}{} % an empty environment to be redefined in TeX
\usepackage{alltt}
\usepackage{url}
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
\begin{document}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
knit_hooks$\hlfunctioncall{set}(wrapper = \hlfunctioncall{function}(before, options, envir) \{
\hlfunctioncall{sprintf}(\hlstring{"\textbackslash{}\textbackslash{}begin\{alltt\}%s\textbackslash{}n\textbackslash{}\textbackslash{}end\{alltt\}"}, \hlfunctioncall{if} (before)
\hlfunctioncall{sprintf}(\hlstring{"<<%s>>="}, options$params.src) else \hlstring{"@"})
\})
\end{alltt}
\end{kframe}
\end{knitrout}
I want to display \verb|<<>>=| in the output since I'm writing a tutorial:
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}<<test_label, wrapper=TRUE, eval=FALSE>>=
1 + 1
\hlfunctioncall{plot}(1)
@
\end{alltt}\end{kframe}
\end{knitrout}
Another approach was mentioned in FAQ 9 (\url{https://github.com/yihui/knitr/blob/master/FAQ.md}), i.e. destroy the chunk header. Here is an example:
\begin{verbatim}
<<test_label, echo=1:2>>=
1 + 1
rnorm(10)
2 + 2
@
\end{verbatim}
\end{document}

Use the figure tag for Markdown

By defautl ![...](...) is translated to <img src='...' alt='...'> in Markdown. This demo shows how to use the HTML5 <figure> tag:

knit_hooks$set(plot = function(x, options) {
    paste("<figure><img src=\"", opts_knit$get("base.url"), paste(x, collapse = "."), 
        "\"><figcaption>", options$fig.cap, "</figcaption></figure>", sep = "")
})

Test:

plot(rnorm(100))

Some random numbers.

This is a very simple-minded plot hook; you should take a look at knitr's default definition if you want to improve this hook function.

# Use the `figure` tag for Markdown
By defautl `![...](...)` is translated to `<img src='...' alt='...'>` in Markdown. This demo shows how to use the HTML5 `<figure>` tag:
```{r setup}
knit_hooks$set(plot = function(x, options) {
paste('<figure><img src="',
opts_knit$get('base.url'), paste(x, collapse = '.'),
'"><figcaption>', options$fig.cap, '</figcaption></figure>',
sep = '')
})
```
Test:
```{r test-plot, fig.cap='Some random numbers.'}
plot(rnorm(100))
```
This is a very simple-minded `plot` hook; you should take a look at [knitr's default definition](https://github.com/yihui/knitr/blob/master/R/hooks-md.R) if you want to improve this hook function.
\documentclass{article}
\usepackage{tikz}
\begin{document}
We cite \cite{lamport94} in this article.
<<bib-plot, dev='tikz', external=FALSE, fig.height=3, fig.width=4>>=
par(mar = c(4.5, 4, .1, .1))
plot(rnorm(100), xlab = 'See \\cite{lamport94} for details')
@
\begin{thebibliography}{9}
\bibitem{lamport94}
Leslie Lamport,
\emph{\LaTeX: A Document Preparation System}.
Addison Wesley, Massachusetts,
2nd Edition,
1994.
\end{thebibliography}
\end{document}
\documentclass{article}\usepackage[]{graphicx}\usepackage[]{color}
%% maxwidth is the original width if it is less than linewidth
%% otherwise use linewidth (to make sure the graphics do not exceed the margin)
\makeatletter
\def\maxwidth{ %
\ifdim\Gin@nat@width>\linewidth
\linewidth
\else
\Gin@nat@width
\fi
}
\makeatother
\definecolor{fgcolor}{rgb}{0.2, 0.2, 0.2}
\newcommand{\hlnumber}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlfunctioncall}[1]{\textcolor[rgb]{0.501960784313725,0,0.329411764705882}{\textbf{#1}}}%
\newcommand{\hlstring}[1]{\textcolor[rgb]{0.6,0.6,1}{#1}}%
\newcommand{\hlkeyword}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlargument}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlcomment}[1]{\textcolor[rgb]{0.180392156862745,0.6,0.341176470588235}{#1}}%
\newcommand{\hlroxygencomment}[1]{\textcolor[rgb]{0.43921568627451,0.47843137254902,0.701960784313725}{#1}}%
\newcommand{\hlformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hleqformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlassignement}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlpackage}[1]{\textcolor[rgb]{0.588235294117647,0.709803921568627,0.145098039215686}{#1}}%
\newcommand{\hlslot}[1]{\textit{#1}}%
\newcommand{\hlsymbol}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlprompt}[1]{\textcolor[rgb]{0.2,0.2,0.2}{#1}}%
\usepackage{framed}
\makeatletter
\newenvironment{kframe}{%
\def\at@end@of@kframe{}%
\ifinner\ifhmode%
\def\at@end@of@kframe{\end{minipage}}%
\begin{minipage}{\columnwidth}%
\fi\fi%
\def\FrameCommand##1{\hskip\@totalleftmargin \hskip-\fboxsep
\colorbox{shadecolor}{##1}\hskip-\fboxsep
% There is no \\@totalrightmargin, so:
\hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth}%
\MakeFramed {\advance\hsize-\width
\@totalleftmargin\z@ \linewidth\hsize
\@setminipage}}%
{\par\unskip\endMakeFramed%
\at@end@of@kframe}
\makeatother
\definecolor{shadecolor}{rgb}{.97, .97, .97}
\definecolor{messagecolor}{rgb}{0, 0, 0}
\definecolor{warningcolor}{rgb}{1, 0, 1}
\definecolor{errorcolor}{rgb}{1, 0, 0}
\newenvironment{knitrout}{}{} % an empty environment to be redefined in TeX
\usepackage{alltt}
\usepackage{tikz}
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
\begin{document}
We cite \cite{lamport94} in this article.
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\begin{kframe}
\begin{alltt}
\hlfunctioncall{par}(mar = \hlfunctioncall{c}(4.5, 4, 0.1, 0.1))
\hlfunctioncall{plot}(\hlfunctioncall{rnorm}(100), xlab = \hlstring{"See \textbackslash{}\textbackslash{}cite\{lamport94\} for details"})
\end{alltt}
\end{kframe}
\input{figure/064-bib-plot-bib-plot.tikz}
\end{knitrout}
\begin{thebibliography}{9}
\bibitem{lamport94}
Leslie Lamport,
\emph{\LaTeX: A Document Preparation System}.
Addison Wesley, Massachusetts,
2nd Edition,
1994.
\end{thebibliography}
\end{document}

Print a code chunk as is

Sometimes we do not want to evaluate a chunk, and we just want to include a chunk literally, e.g. when writing tutorials. Two examples have been given:

The R code chunks in these examples are still identified by knitr. If we do not want to evaluate the code at all, there is another approach, which is to break the chunk syntax by adding an empty string as inline R code.

For Markdown, we can add an empty string after ```{r}; knitr will ignore this code chunk but also replace inline R code with the empty string. Here is one example (it is indented by 4 spaces because we want to show it in a preformatted block in the HTML output):

```{r eval=TRUE}
n = 10
rnorm(x)
```

By comparison, this chunk will be identified by knitr as usual:

n = 10
rnorm(n)
##  [1] -0.56048 -0.23018  1.55871  0.07051  0.12929  1.71506  0.46092
##  [8] -1.26506 -0.68685 -0.44566
# Print a code chunk as is
Sometimes we do not want to evaluate a chunk, and we just want to include a chunk literally, e.g. when writing tutorials. Two examples have been given:
- [062-chunk-wrapper.Rmd](https://github.com/yihui/knitr-examples/blob/master/062-chunk-wrapper.Rmd) ([output](https://github.com/yihui/knitr-examples/blob/master/062-chunk-wrapper.md))
- [062-chunk-wrapper.Rnw](https://github.com/yihui/knitr-examples/blob/master/062-chunk-wrapper.Rnw) ([output](https://github.com/yihui/knitr-examples/blob/master/062-chunk-wrapper.tex))
The R code chunks in these examples are still identified by **knitr**. If we do not want to evaluate the code at all, there is another approach, which is to break the chunk syntax by adding an empty string as _inline R code_.
For Markdown, we can add an empty string after ```` ```{r} ````; **knitr** will ignore this code chunk but also replace inline R code with the empty string. Here is one example (it is indented by 4 spaces because we want to show it in a preformatted block in the HTML output):
```{r eval=TRUE}`r ''`
n = 10
rnorm(x)
```
By comparison, this chunk will be identified by **knitr** as usual:
```{r eval=TRUE}
n = 10
rnorm(n)
```
\documentclass[preview]{standalone}
\lstset{breaklines=true} % break long lines
<<setup, include=FALSE>>=
render_listings()
@
\begin{document}
We can set the \texttt{breaklines} option to \texttt{true} to wrap long lines.
<<long-print>>=
print("asdlfjk sadflkj kljsd klwjr klwjre klwjer kljwre kljwer lkjrwee lkwjre lkwjere lkwjer lkwjre lkasdfa afsd afdafsd afddadf adfsadf afdasdf")
@
By comparison, this shows \texttt{breaklines=false}:
\lstset{breaklines=false} % break long lines
<<long-print>>=
@
\end{document}
\documentclass[preview]{standalone}\usepackage[]{graphicx}\usepackage[]{color}
%% maxwidth is the original width if it is less than linewidth
%% otherwise use linewidth (to make sure the graphics do not exceed the margin)
\makeatletter
\def\maxwidth{ %
\ifdim\Gin@nat@width>\linewidth
\linewidth
\else
\Gin@nat@width
\fi
}
\makeatother
\usepackage{Sweavel}
\lstset{breaklines=true} % break long lines
\begin{document}
We can set the \texttt{breaklines} option to \texttt{true} to wrap long lines.
\begin{Schunk}
\begin{Sinput}
print("asdlfjk sadflkj kljsd klwjr klwjre klwjer kljwre kljwer lkjrwee lkwjre lkwjere lkwjer lkwjre lkasdfa afsd afdafsd afddadf adfsadf afdasdf")
\end{Sinput}
\begin{Soutput}
[1] "asdlfjk sadflkj kljsd klwjr klwjre klwjer kljwre kljwer lkjrwee lkwjre lkwjere lkwjer lkwjre lkasdfa afsd afdafsd afddadf adfsadf afdasdf"
\end{Soutput}
\end{Schunk}
By comparison, this shows \texttt{breaklines=false}:
\lstset{breaklines=false} % break long lines
\begin{Schunk}
\begin{Sinput}
print("asdlfjk sadflkj kljsd klwjr klwjre klwjer kljwre kljwer lkjrwee lkwjre lkwjere lkwjer lkwjre lkasdfa afsd afdafsd afddadf adfsadf afdasdf")
\end{Sinput}
\begin{Soutput}
[1] "asdlfjk sadflkj kljsd klwjr klwjre klwjer kljwre kljwer lkjrwee lkwjre lkwjere lkwjer lkwjre lkasdfa afsd afdafsd afddadf adfsadf afdasdf"
\end{Soutput}
\end{Schunk}
\end{document}
\documentclass{article}
\usepackage{float} % for fig.pos='H'
\usepackage{rotfloat} % for sidewaysfigure
\usepackage{subfig} % for subfigure
\title{Graphics Options in knitr}
\author{Yihui Xie}
\begin{document}
\maketitle
<<setup, include=FALSE>>=
opts_chunk$set(fig.width=4, fig.height=3, par=TRUE, out.width='2in', fig.pos='H')
knit_hooks$set(par = function(before, options, envir) {
if (before) par(mar = c(4, 4, .1, .1))
})
set.seed(123)
@
These options are vectorized for multiple plots per chunk: \Sexpr{knitr:::.recyle.opts}. When the plot hook is called, the i-th elements of these options will be applied to the i-th plot.
Figure captions. Look at Figure \ref{fig:fig-cap1} and \ref{fig:fig-cap2}.
<<fig-cap, fig.cap=c('One plot.', 'Another plot.')>>=
par(bg=rgb(runif(1), runif(1), runif(1)))
plot(1:10)
plot(rnorm(10), pch=19)
@
Different out.width and out.height.
<<fig-out, ref.label='fig-cap', out.width=c('1in', '.4\\linewidth')>>=
@
Different out.extra (rotate by different degrees).
<<fig-extra, ref.label='fig-cap', out.extra=sprintf('angle=%d', c(30,120))>>=
@
Short options will be recycled: out.width below is of length 1 but there are two plots.
<<fig-width, ref.label='fig-cap', out.width='1in'>>=
@
Use subfigures for each plot. Look at Figure \ref{fig:fig-sub1} and \ref{fig:fig-sub2}.
<<fig-sub, ref.label='fig-cap', fig.cap='two plots', fig.subcap=c('one plot', 'the other one'), out.width='.49\\linewidth'>>=
@
The second figure uses sidewaysfigure (i.e. Figure \ref{fig:fig-margin2}).
<<fig-margin, ref.label='fig-cap', fig.cap=c('ordinary figure', 'sideways figure'), fig.env=c('figure', 'sidewaysfigure')>>=
@
\end{document}
\documentclass{article}\usepackage[]{graphicx}\usepackage[]{color}
%% maxwidth is the original width if it is less than linewidth
%% otherwise use linewidth (to make sure the graphics do not exceed the margin)
\makeatletter
\def\maxwidth{ %
\ifdim\Gin@nat@width>\linewidth
\linewidth
\else
\Gin@nat@width
\fi
}
\makeatother
\definecolor{fgcolor}{rgb}{0.2, 0.2, 0.2}
\newcommand{\hlnumber}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlfunctioncall}[1]{\textcolor[rgb]{0.501960784313725,0,0.329411764705882}{\textbf{#1}}}%
\newcommand{\hlstring}[1]{\textcolor[rgb]{0.6,0.6,1}{#1}}%
\newcommand{\hlkeyword}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlargument}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlcomment}[1]{\textcolor[rgb]{0.180392156862745,0.6,0.341176470588235}{#1}}%
\newcommand{\hlroxygencomment}[1]{\textcolor[rgb]{0.43921568627451,0.47843137254902,0.701960784313725}{#1}}%
\newcommand{\hlformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hleqformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlassignement}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlpackage}[1]{\textcolor[rgb]{0.588235294117647,0.709803921568627,0.145098039215686}{#1}}%
\newcommand{\hlslot}[1]{\textit{#1}}%
\newcommand{\hlsymbol}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlprompt}[1]{\textcolor[rgb]{0.2,0.2,0.2}{#1}}%
\usepackage{framed}
\makeatletter
\newenvironment{kframe}{%
\def\at@end@of@kframe{}%
\ifinner\ifhmode%
\def\at@end@of@kframe{\end{minipage}}%
\begin{minipage}{\columnwidth}%
\fi\fi%
\def\FrameCommand##1{\hskip\@totalleftmargin \hskip-\fboxsep
\colorbox{shadecolor}{##1}\hskip-\fboxsep
% There is no \\@totalrightmargin, so:
\hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth}%
\MakeFramed {\advance\hsize-\width
\@totalleftmargin\z@ \linewidth\hsize
\@setminipage}}%
{\par\unskip\endMakeFramed%
\at@end@of@kframe}
\makeatother
\definecolor{shadecolor}{rgb}{.97, .97, .97}
\definecolor{messagecolor}{rgb}{0, 0, 0}
\definecolor{warningcolor}{rgb}{1, 0, 1}
\definecolor{errorcolor}{rgb}{1, 0, 0}
\newenvironment{knitrout}{}{} % an empty environment to be redefined in TeX
\usepackage{alltt}
\usepackage{float} % for fig.pos='H'
\usepackage{rotfloat} % for sidewaysfigure
\usepackage{subfig} % for subfigure
\title{Graphics Options in knitr}
\author{Yihui Xie}
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
\begin{document}
\maketitle
These options are vectorized for multiple plots per chunk: fig.cap, fig.scap, fig.env, fig.pos, fig.subcap, out.width, out.height, out.extra. When the plot hook is called, the i-th elements of these options will be applied to the i-th plot.
Figure captions. Look at Figure \ref{fig:fig-cap1} and \ref{fig:fig-cap2}.
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlfunctioncall{par}(bg = \hlfunctioncall{rgb}(\hlfunctioncall{runif}(1), \hlfunctioncall{runif}(1), \hlfunctioncall{runif}(1)))
\hlfunctioncall{plot}(1:10)
\end{alltt}
\end{kframe}\begin{figure}[H]
\includegraphics[width=2in]{figure/067-graphics-options-fig-cap1} \caption[One plot]{One plot.\label{fig:fig-cap1}}
\end{figure}
\begin{kframe}\begin{alltt}
\hlfunctioncall{plot}(\hlfunctioncall{rnorm}(10), pch = 19)
\end{alltt}
\end{kframe}\begin{figure}[H]
\includegraphics[width=2in]{figure/067-graphics-options-fig-cap2} \caption[Another plot]{Another plot.\label{fig:fig-cap2}}
\end{figure}
\end{knitrout}
Different out.width and out.height.
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlfunctioncall{par}(bg = \hlfunctioncall{rgb}(\hlfunctioncall{runif}(1), \hlfunctioncall{runif}(1), \hlfunctioncall{runif}(1)))
\hlfunctioncall{plot}(1:10)
\end{alltt}
\end{kframe}
\includegraphics[width=1in]{figure/067-graphics-options-fig-out1}
\begin{kframe}\begin{alltt}
\hlfunctioncall{plot}(\hlfunctioncall{rnorm}(10), pch = 19)
\end{alltt}
\end{kframe}
\includegraphics[width=.4\linewidth]{figure/067-graphics-options-fig-out2}
\end{knitrout}
Different out.extra (rotate by different degrees).
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlfunctioncall{par}(bg = \hlfunctioncall{rgb}(\hlfunctioncall{runif}(1), \hlfunctioncall{runif}(1), \hlfunctioncall{runif}(1)))
\hlfunctioncall{plot}(1:10)
\end{alltt}
\end{kframe}
\includegraphics[width=2in,angle=30]{figure/067-graphics-options-fig-extra1}
\begin{kframe}\begin{alltt}
\hlfunctioncall{plot}(\hlfunctioncall{rnorm}(10), pch = 19)
\end{alltt}
\end{kframe}
\includegraphics[width=2in,angle=120]{figure/067-graphics-options-fig-extra2}
\end{knitrout}
Short options will be recycled: out.width below is of length 1 but there are two plots.
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlfunctioncall{par}(bg = \hlfunctioncall{rgb}(\hlfunctioncall{runif}(1), \hlfunctioncall{runif}(1), \hlfunctioncall{runif}(1)))
\hlfunctioncall{plot}(1:10)
\end{alltt}
\end{kframe}
\includegraphics[width=1in]{figure/067-graphics-options-fig-width1}
\begin{kframe}\begin{alltt}
\hlfunctioncall{plot}(\hlfunctioncall{rnorm}(10), pch = 19)
\end{alltt}
\end{kframe}
\includegraphics[width=1in]{figure/067-graphics-options-fig-width2}
\end{knitrout}
Use subfigures for each plot. Look at Figure \ref{fig:fig-sub1} and \ref{fig:fig-sub2}.
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlfunctioncall{par}(bg = \hlfunctioncall{rgb}(\hlfunctioncall{runif}(1), \hlfunctioncall{runif}(1), \hlfunctioncall{runif}(1)))
\hlfunctioncall{plot}(1:10)
\hlfunctioncall{plot}(\hlfunctioncall{rnorm}(10), pch = 19)
\end{alltt}
\end{kframe}\begin{figure}[H]
\subfloat[one plot\label{fig:fig-sub1}]{
\includegraphics[width=.49\linewidth]{figure/067-graphics-options-fig-sub1} }
\subfloat[the other one\label{fig:fig-sub2}]{
\includegraphics[width=.49\linewidth]{figure/067-graphics-options-fig-sub2} }\caption[two plots]{two plots\label{fig:fig-sub}}
\end{figure}
\end{knitrout}
The second figure uses sidewaysfigure (i.e. Figure \ref{fig:fig-margin2}).
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlfunctioncall{par}(bg = \hlfunctioncall{rgb}(\hlfunctioncall{runif}(1), \hlfunctioncall{runif}(1), \hlfunctioncall{runif}(1)))
\hlfunctioncall{plot}(1:10)
\end{alltt}
\end{kframe}\begin{figure}[H]
\includegraphics[width=2in]{figure/067-graphics-options-fig-margin1} \caption[ordinary figure]{ordinary figure\label{fig:fig-margin1}}
\end{figure}
\begin{kframe}\begin{alltt}
\hlfunctioncall{plot}(\hlfunctioncall{rnorm}(10), pch = 19)
\end{alltt}
\end{kframe}\begin{sidewaysfigure}[H]
\includegraphics[width=2in]{figure/067-graphics-options-fig-margin2} \caption[sideways figure]{sideways figure\label{fig:fig-margin2}}
\end{sidewaysfigure}
\end{knitrout}
\end{document}
\documentclass{beamer}
\begin{document}
\title{Using knitr in Beamer}
\author{Yihui Xie}
\maketitle
\begin{frame}
\frametitle{Introduction}
This is a normal slide.
\end{frame}
% need the option [fragile] for code output!
\begin{frame}[fragile]
\frametitle{Code chunks}
<<test, out.width='.6\\linewidth', fig.align='center'>>=
par(mar = c(4, 4, .1, .1))
x = rnorm(100)
hist(x, main='', col='lightblue', border='white')
rug(x)
@
\end{frame}
\end{document}
\documentclass{beamer}\usepackage[]{graphicx}\usepackage[]{color}
%% maxwidth is the original width if it is less than linewidth
%% otherwise use linewidth (to make sure the graphics do not exceed the margin)
\makeatletter
\def\maxwidth{ %
\ifdim\Gin@nat@width>\linewidth
\linewidth
\else
\Gin@nat@width
\fi
}
\makeatother
\definecolor{fgcolor}{rgb}{0.2, 0.2, 0.2}
\newcommand{\hlnumber}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlfunctioncall}[1]{\textcolor[rgb]{0.501960784313725,0,0.329411764705882}{\textbf{#1}}}%
\newcommand{\hlstring}[1]{\textcolor[rgb]{0.6,0.6,1}{#1}}%
\newcommand{\hlkeyword}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlargument}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlcomment}[1]{\textcolor[rgb]{0.180392156862745,0.6,0.341176470588235}{#1}}%
\newcommand{\hlroxygencomment}[1]{\textcolor[rgb]{0.43921568627451,0.47843137254902,0.701960784313725}{#1}}%
\newcommand{\hlformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hleqformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlassignement}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlpackage}[1]{\textcolor[rgb]{0.588235294117647,0.709803921568627,0.145098039215686}{#1}}%
\newcommand{\hlslot}[1]{\textit{#1}}%
\newcommand{\hlsymbol}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlprompt}[1]{\textcolor[rgb]{0.2,0.2,0.2}{#1}}%
\usepackage{framed}
\makeatletter
\newenvironment{kframe}{%
\def\at@end@of@kframe{}%
\ifinner\ifhmode%
\def\at@end@of@kframe{\end{minipage}}%
\begin{minipage}{\columnwidth}%
\fi\fi%
\def\FrameCommand##1{\hskip\@totalleftmargin \hskip-\fboxsep
\colorbox{shadecolor}{##1}\hskip-\fboxsep
% There is no \\@totalrightmargin, so:
\hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth}%
\MakeFramed {\advance\hsize-\width
\@totalleftmargin\z@ \linewidth\hsize
\@setminipage}}%
{\par\unskip\endMakeFramed%
\at@end@of@kframe}
\makeatother
\definecolor{shadecolor}{rgb}{.97, .97, .97}
\definecolor{messagecolor}{rgb}{0, 0, 0}
\definecolor{warningcolor}{rgb}{1, 0, 1}
\definecolor{errorcolor}{rgb}{1, 0, 0}
\newenvironment{knitrout}{}{} % an empty environment to be redefined in TeX
\usepackage{alltt}
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
\begin{document}
\title{Using knitr in Beamer}
\author{Yihui Xie}
\maketitle
\begin{frame}
\frametitle{Introduction}
This is a normal slide.
\end{frame}
% need the option [fragile] for code output!
\begin{frame}[fragile]
\frametitle{Code chunks}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlfunctioncall{par}(mar = \hlfunctioncall{c}(4, 4, 0.1, 0.1))
x = \hlfunctioncall{rnorm}(100)
\hlfunctioncall{hist}(x, main = \hlstring{""}, col = \hlstring{"lightblue"}, border = \hlstring{"white"})
\hlfunctioncall{rug}(x)
\end{alltt}
\end{kframe}
{\centering \includegraphics[width=.6\linewidth]{figure/068-beamer-simple-test}
}
\end{knitrout}
\end{frame}
\end{document}
\documentclass{article}
\begin{document}
Collect results from the template for each i and write them back later.
<<run-all, include=FALSE>>=
src <- NULL
for (i in 1:3) {
src <- c(src, knit(text = readLines("069-for-template.rnw")))
}
out <- knit (text = src)
@
\Sexpr{paste(out, collapse = '\n')}
\end{document}
\documentclass{article}\usepackage[]{graphicx}\usepackage[]{color}
%% maxwidth is the original width if it is less than linewidth
%% otherwise use linewidth (to make sure the graphics do not exceed the margin)
\makeatletter
\def\maxwidth{ %
\ifdim\Gin@nat@width>\linewidth
\linewidth
\else
\Gin@nat@width
\fi
}
\makeatother
\definecolor{fgcolor}{rgb}{0.2, 0.2, 0.2}
\newcommand{\hlnumber}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlfunctioncall}[1]{\textcolor[rgb]{0.501960784313725,0,0.329411764705882}{\textbf{#1}}}%
\newcommand{\hlstring}[1]{\textcolor[rgb]{0.6,0.6,1}{#1}}%
\newcommand{\hlkeyword}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlargument}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlcomment}[1]{\textcolor[rgb]{0.180392156862745,0.6,0.341176470588235}{#1}}%
\newcommand{\hlroxygencomment}[1]{\textcolor[rgb]{0.43921568627451,0.47843137254902,0.701960784313725}{#1}}%
\newcommand{\hlformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hleqformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlassignement}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlpackage}[1]{\textcolor[rgb]{0.588235294117647,0.709803921568627,0.145098039215686}{#1}}%
\newcommand{\hlslot}[1]{\textit{#1}}%
\newcommand{\hlsymbol}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlprompt}[1]{\textcolor[rgb]{0.2,0.2,0.2}{#1}}%
\usepackage{framed}
\makeatletter
\newenvironment{kframe}{%
\def\at@end@of@kframe{}%
\ifinner\ifhmode%
\def\at@end@of@kframe{\end{minipage}}%
\begin{minipage}{\columnwidth}%
\fi\fi%
\def\FrameCommand##1{\hskip\@totalleftmargin \hskip-\fboxsep
\colorbox{shadecolor}{##1}\hskip-\fboxsep
% There is no \\@totalrightmargin, so:
\hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth}%
\MakeFramed {\advance\hsize-\width
\@totalleftmargin\z@ \linewidth\hsize
\@setminipage}}%
{\par\unskip\endMakeFramed%
\at@end@of@kframe}
\makeatother
\definecolor{shadecolor}{rgb}{.97, .97, .97}
\definecolor{messagecolor}{rgb}{0, 0, 0}
\definecolor{warningcolor}{rgb}{1, 0, 1}
\definecolor{errorcolor}{rgb}{1, 0, 0}
\newenvironment{knitrout}{}{} % an empty environment to be redefined in TeX
\usepackage{alltt}
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
\begin{document}
Collect results from the template for each i and write them back later.
\section{Now i is 1}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlfunctioncall{print}(1)
\end{alltt}
\begin{verbatim}
## [1] 1
\end{verbatim}
\begin{alltt}
iris[1, ]
\end{alltt}
\begin{verbatim}
## Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1 5.1 3.5 1.4 0.2 setosa
\end{verbatim}
\begin{alltt}
\hlfunctioncall{boxplot}(iris[, 1] ~ iris$Species)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/069-for-loop-arbitrary-chunk-label-1-here}
\end{knitrout}
\section{Now i is 2}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlfunctioncall{print}(2)
\end{alltt}
\begin{verbatim}
## [1] 2
\end{verbatim}
\begin{alltt}
iris[2, ]
\end{alltt}
\begin{verbatim}
## Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 2 4.9 3 1.4 0.2 setosa
\end{verbatim}
\begin{alltt}
\hlfunctioncall{boxplot}(iris[, 2] ~ iris$Species)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/069-for-loop-arbitrary-chunk-label-2-here}
\end{knitrout}
\section{Now i is 3}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlfunctioncall{print}(3)
\end{alltt}
\begin{verbatim}
## [1] 3
\end{verbatim}
\begin{alltt}
iris[3, ]
\end{alltt}
\begin{verbatim}
## Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 3 4.7 3.2 1.3 0.2 setosa
\end{verbatim}
\begin{alltt}
\hlfunctioncall{boxplot}(iris[, 3] ~ iris$Species)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/069-for-loop-arbitrary-chunk-label-3-here}
\end{knitrout}
\end{document}
\section{Now i is \Sexpr{i}}
\Sexpr{''}<<\Sexpr{paste('arbitrary-chunk-label-', i, '-here', sep = '')}>>=
print (\Sexpr{i})
iris[\Sexpr{i}, ]
boxplot (iris[, \Sexpr{i}] ~ iris$Species)
@

Incremental Figure Numbers

plot(1:10)

Figure 1: this is one plot

plot(rnorm(10))

Figure 2: another plot

# Incremental Figure Numbers
```{r setup, include=FALSE}
fn = local({
i = 0
function(x) {
i <<- i + 1
paste('Figure ', i, ': ', x, sep = '')
}
})
```
```{r test-a, fig.cap=fn('this is one plot')}
plot(1:10)
```
```{r test-b, fig.cap=fn('another plot')}
plot(rnorm(10))
```
\documentclass{article}
\usepackage{amsthm}
\newtheorem{rexample}{R Example}[section]
\usepackage{cleveref}
\crefname{rexample}{R Example}{R Examples}
\title{Using cleveref with knitr}
\author{Yihui Xie}
\begin{document}
\maketitle
<<setup, include=FALSE>>=
knit_hooks$set(rexample = function(before, options, envir) {
if (before) sprintf('\\begin{rexample}\\label{%s}\\hfill{}', options$label) else '\\end{rexample}'
})
@
\section{cleveref with R examples}
A test of the R Example environment.
\subsection{Go!}
<<test-a, rexample=TRUE>>=
1+1
@
Look at \cref{test-a}!
\subsection{Ha!}
<<test-b, rexample=TRUE>>=
x=rnorm(10)
@
Move on!
<<test-c, rexample=TRUE>>=
sd(x) # standard deviation
@
How about \cref{test-b,test-c}?
If you want to use this R Example environment for all code chunks, make rexample a global chunk option in the setup chunk.
\end{document}
\documentclass{article}\usepackage[]{graphicx}\usepackage[]{color}
%% maxwidth is the original width if it is less than linewidth
%% otherwise use linewidth (to make sure the graphics do not exceed the margin)
\makeatletter
\def\maxwidth{ %
\ifdim\Gin@nat@width>\linewidth
\linewidth
\else
\Gin@nat@width
\fi
}
\makeatother
\definecolor{fgcolor}{rgb}{0.2, 0.2, 0.2}
\newcommand{\hlnumber}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlfunctioncall}[1]{\textcolor[rgb]{0.501960784313725,0,0.329411764705882}{\textbf{#1}}}%
\newcommand{\hlstring}[1]{\textcolor[rgb]{0.6,0.6,1}{#1}}%
\newcommand{\hlkeyword}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlargument}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlcomment}[1]{\textcolor[rgb]{0.180392156862745,0.6,0.341176470588235}{#1}}%
\newcommand{\hlroxygencomment}[1]{\textcolor[rgb]{0.43921568627451,0.47843137254902,0.701960784313725}{#1}}%
\newcommand{\hlformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hleqformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlassignement}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlpackage}[1]{\textcolor[rgb]{0.588235294117647,0.709803921568627,0.145098039215686}{#1}}%
\newcommand{\hlslot}[1]{\textit{#1}}%
\newcommand{\hlsymbol}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlprompt}[1]{\textcolor[rgb]{0.2,0.2,0.2}{#1}}%
\usepackage{framed}
\makeatletter
\newenvironment{kframe}{%
\def\at@end@of@kframe{}%
\ifinner\ifhmode%
\def\at@end@of@kframe{\end{minipage}}%
\begin{minipage}{\columnwidth}%
\fi\fi%
\def\FrameCommand##1{\hskip\@totalleftmargin \hskip-\fboxsep
\colorbox{shadecolor}{##1}\hskip-\fboxsep
% There is no \\@totalrightmargin, so:
\hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth}%
\MakeFramed {\advance\hsize-\width
\@totalleftmargin\z@ \linewidth\hsize
\@setminipage}}%
{\par\unskip\endMakeFramed%
\at@end@of@kframe}
\makeatother
\definecolor{shadecolor}{rgb}{.97, .97, .97}
\definecolor{messagecolor}{rgb}{0, 0, 0}
\definecolor{warningcolor}{rgb}{1, 0, 1}
\definecolor{errorcolor}{rgb}{1, 0, 0}
\newenvironment{knitrout}{}{} % an empty environment to be redefined in TeX
\usepackage{alltt}
\usepackage{amsthm}
\newtheorem{rexample}{R Example}[section]
\usepackage{cleveref}
\crefname{rexample}{R Example}{R Examples}
\title{Using cleveref with knitr}
\author{Yihui Xie}
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
\begin{document}
\maketitle
\section{cleveref with R examples}
A test of the R Example environment.
\subsection{Go!}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{rexample}\label{test-a}\hfill{}\begin{alltt}
1 + 1
\end{alltt}
\begin{verbatim}
## [1] 2
\end{verbatim}
\end{rexample}\end{kframe}
\end{knitrout}
Look at \cref{test-a}!
\subsection{Ha!}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{rexample}\label{test-b}\hfill{}\begin{alltt}
x = \hlfunctioncall{rnorm}(10)
\end{alltt}
\end{rexample}\end{kframe}
\end{knitrout}
Move on!
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{rexample}\label{test-c}\hfill{}\begin{alltt}
\hlfunctioncall{sd}(x) \hlcomment{# standard deviation}
\end{alltt}
\begin{verbatim}
## [1] 0.9538
\end{verbatim}
\end{rexample}\end{kframe}
\end{knitrout}
How about \cref{test-b,test-c}?
If you want to use this R Example environment for all code chunks, make rexample a global chunk option in the setup chunk.
\end{document}
\documentclass{article}
\usepackage{url}
\begin{document}
Restore \verb|\textbackslash{}ref\{\}| to \verb|\ref{}| in the output so we can use references in source code (see \url{http://stackoverflow.com/q/14058832/559676}).
<<setup, include=FALSE>>=
hook_source = knit_hooks$get('source')
knit_hooks$set(source = function(x, options) {
txt = hook_source(x, options)
# extend the default source hook
gsub('\\\\textbackslash\\{\\}ref\\\\\\{(.+)\\\\\\}', '\\\\ref{\\1}', txt)
})
@
<<"example", fig.cap = "some figure">>=
# the following code generated Figure \ref{fig:example}
plot(1:10, 1:10)
@
\end{document}
\documentclass{article}\usepackage[]{graphicx}\usepackage[]{color}
%% maxwidth is the original width if it is less than linewidth
%% otherwise use linewidth (to make sure the graphics do not exceed the margin)
\makeatletter
\def\maxwidth{ %
\ifdim\Gin@nat@width>\linewidth
\linewidth
\else
\Gin@nat@width
\fi
}
\makeatother
\definecolor{fgcolor}{rgb}{0.2, 0.2, 0.2}
\newcommand{\hlnumber}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlfunctioncall}[1]{\textcolor[rgb]{0.501960784313725,0,0.329411764705882}{\textbf{#1}}}%
\newcommand{\hlstring}[1]{\textcolor[rgb]{0.6,0.6,1}{#1}}%
\newcommand{\hlkeyword}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlargument}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlcomment}[1]{\textcolor[rgb]{0.180392156862745,0.6,0.341176470588235}{#1}}%
\newcommand{\hlroxygencomment}[1]{\textcolor[rgb]{0.43921568627451,0.47843137254902,0.701960784313725}{#1}}%
\newcommand{\hlformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hleqformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlassignement}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlpackage}[1]{\textcolor[rgb]{0.588235294117647,0.709803921568627,0.145098039215686}{#1}}%
\newcommand{\hlslot}[1]{\textit{#1}}%
\newcommand{\hlsymbol}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlprompt}[1]{\textcolor[rgb]{0.2,0.2,0.2}{#1}}%
\usepackage{framed}
\makeatletter
\newenvironment{kframe}{%
\def\at@end@of@kframe{}%
\ifinner\ifhmode%
\def\at@end@of@kframe{\end{minipage}}%
\begin{minipage}{\columnwidth}%
\fi\fi%
\def\FrameCommand##1{\hskip\@totalleftmargin \hskip-\fboxsep
\colorbox{shadecolor}{##1}\hskip-\fboxsep
% There is no \\@totalrightmargin, so:
\hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth}%
\MakeFramed {\advance\hsize-\width
\@totalleftmargin\z@ \linewidth\hsize
\@setminipage}}%
{\par\unskip\endMakeFramed%
\at@end@of@kframe}
\makeatother
\definecolor{shadecolor}{rgb}{.97, .97, .97}
\definecolor{messagecolor}{rgb}{0, 0, 0}
\definecolor{warningcolor}{rgb}{1, 0, 1}
\definecolor{errorcolor}{rgb}{1, 0, 0}
\newenvironment{knitrout}{}{} % an empty environment to be redefined in TeX
\usepackage{alltt}
\usepackage{url}
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
\begin{document}
Restore \verb|\textbackslash{}ref\{\}| to \verb|\ref{}| in the output so we can use references in source code (see \url{http://stackoverflow.com/q/14058832/559676}).
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlcomment{# the following code generated Figure \ref{fig:example}}
\hlfunctioncall{plot}(1:10, 1:10)
\end{alltt}
\end{kframe}\begin{figure}[]
\includegraphics[width=\maxwidth]{figure/072-latex-reference-example} \caption[some figure]{some figure\label{fig:example}}
\end{figure}
\end{knitrout}
\end{document}
\documentclass{article}
\begin{document}
\section{Introduction}
Move all code chunks into the appendix.
\section{Computing}
<<setup, include=FALSE>>=
opts_chunk$set(echo=FALSE) # hide source code in the document
@
You cannot see the source code because echo = FALSE was set globally.
<<a>>=
# chunk a
1+1
@
<<b>>=
# chunk b
2+2
@
<<c>>=
# chunk c
rnorm(10)
@
\appendix
\section{Source code}
Now we show all the code chunks:
<<all-code, ref.label=all_labels(), echo=TRUE, eval=FALSE>>=
@
Of course, you can select labels to include here, e.g. remove the first chunk:
<<some-code, ref.label=all_labels()[-1], echo=TRUE, eval=FALSE>>=
@
\end{document}
\documentclass{article}\usepackage[]{graphicx}\usepackage[]{color}
%% maxwidth is the original width if it is less than linewidth
%% otherwise use linewidth (to make sure the graphics do not exceed the margin)
\makeatletter
\def\maxwidth{ %
\ifdim\Gin@nat@width>\linewidth
\linewidth
\else
\Gin@nat@width
\fi
}
\makeatother
\definecolor{fgcolor}{rgb}{0.2, 0.2, 0.2}
\newcommand{\hlnumber}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlfunctioncall}[1]{\textcolor[rgb]{0.501960784313725,0,0.329411764705882}{\textbf{#1}}}%
\newcommand{\hlstring}[1]{\textcolor[rgb]{0.6,0.6,1}{#1}}%
\newcommand{\hlkeyword}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlargument}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlcomment}[1]{\textcolor[rgb]{0.180392156862745,0.6,0.341176470588235}{#1}}%
\newcommand{\hlroxygencomment}[1]{\textcolor[rgb]{0.43921568627451,0.47843137254902,0.701960784313725}{#1}}%
\newcommand{\hlformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hleqformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlassignement}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlpackage}[1]{\textcolor[rgb]{0.588235294117647,0.709803921568627,0.145098039215686}{#1}}%
\newcommand{\hlslot}[1]{\textit{#1}}%
\newcommand{\hlsymbol}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlprompt}[1]{\textcolor[rgb]{0.2,0.2,0.2}{#1}}%
\usepackage{framed}
\makeatletter
\newenvironment{kframe}{%
\def\at@end@of@kframe{}%
\ifinner\ifhmode%
\def\at@end@of@kframe{\end{minipage}}%
\begin{minipage}{\columnwidth}%
\fi\fi%
\def\FrameCommand##1{\hskip\@totalleftmargin \hskip-\fboxsep
\colorbox{shadecolor}{##1}\hskip-\fboxsep
% There is no \\@totalrightmargin, so:
\hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth}%
\MakeFramed {\advance\hsize-\width
\@totalleftmargin\z@ \linewidth\hsize
\@setminipage}}%
{\par\unskip\endMakeFramed%
\at@end@of@kframe}
\makeatother
\definecolor{shadecolor}{rgb}{.97, .97, .97}
\definecolor{messagecolor}{rgb}{0, 0, 0}
\definecolor{warningcolor}{rgb}{1, 0, 1}
\definecolor{errorcolor}{rgb}{1, 0, 0}
\newenvironment{knitrout}{}{} % an empty environment to be redefined in TeX
\usepackage{alltt}
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
\begin{document}
\section{Introduction}
Move all code chunks into the appendix.
\section{Computing}
You cannot see the source code because echo = FALSE was set globally.
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{verbatim}
## [1] 2
\end{verbatim}
\end{kframe}
\end{knitrout}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{verbatim}
## [1] 4
\end{verbatim}
\end{kframe}
\end{knitrout}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{verbatim}
## [1] -0.56048 -0.23018 1.55871 0.07051 0.12929 1.71506 0.46092
## [8] -1.26506 -0.68685 -0.44566
\end{verbatim}
\end{kframe}
\end{knitrout}
\appendix
\section{Source code}
Now we show all the code chunks:
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
opts_chunk$\hlfunctioncall{set}(echo = FALSE) \hlcomment{# hide source code in the document}
\hlcomment{# chunk a}
1 + 1
\hlcomment{# chunk b}
2 + 2
\hlcomment{# chunk c}
\hlfunctioncall{rnorm}(10)
\end{alltt}
\end{kframe}
\end{knitrout}
Of course, you can select labels to include here, e.g. remove the first chunk:
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlcomment{# chunk a}
1 + 1
\hlcomment{# chunk b}
2 + 2
\hlcomment{# chunk c}
\hlfunctioncall{rnorm}(10)
\end{alltt}
\end{kframe}
\end{knitrout}
\end{document}
\documentclass{article}
\usepackage{amsthm}
\newtheorem{rexample}{R Example}[section]
\title{Using the Example Environment with knitr}
\author{Yihui Xie}
\begin{document}
\maketitle
<<setup, include=FALSE>>=
knit_hooks$set(rexample = function(before, options, envir) {
if (before) sprintf('\\begin{rexample}\\label{%s}\\hfill{}', options$label) else '\\end{rexample}'
})
@
\section{Introduction}
This is a test of the R Example environment.
\subsection{Go!}
<<test-a, rexample=TRUE>>=
1+1
@
Look at Example \ref{test-a}!
\subsection{Ha!}
<<test-b, rexample=TRUE>>=
x=rnorm(10)
@
Move on!
<<test-c, rexample=TRUE>>=
sd(x) # standard deviation
@
How about \ref{test-b} and \ref{test-c}?
If you want to use this R Example environment for all code chunks, make rexample a global chunk option in the setup chunk.
\end{document}
\documentclass{article}\usepackage[]{graphicx}\usepackage[]{color}
%% maxwidth is the original width if it is less than linewidth
%% otherwise use linewidth (to make sure the graphics do not exceed the margin)
\makeatletter
\def\maxwidth{ %
\ifdim\Gin@nat@width>\linewidth
\linewidth
\else
\Gin@nat@width
\fi
}
\makeatother
\definecolor{fgcolor}{rgb}{0.2, 0.2, 0.2}
\newcommand{\hlnumber}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlfunctioncall}[1]{\textcolor[rgb]{0.501960784313725,0,0.329411764705882}{\textbf{#1}}}%
\newcommand{\hlstring}[1]{\textcolor[rgb]{0.6,0.6,1}{#1}}%
\newcommand{\hlkeyword}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlargument}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlcomment}[1]{\textcolor[rgb]{0.180392156862745,0.6,0.341176470588235}{#1}}%
\newcommand{\hlroxygencomment}[1]{\textcolor[rgb]{0.43921568627451,0.47843137254902,0.701960784313725}{#1}}%
\newcommand{\hlformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hleqformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlassignement}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlpackage}[1]{\textcolor[rgb]{0.588235294117647,0.709803921568627,0.145098039215686}{#1}}%
\newcommand{\hlslot}[1]{\textit{#1}}%
\newcommand{\hlsymbol}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlprompt}[1]{\textcolor[rgb]{0.2,0.2,0.2}{#1}}%
\usepackage{framed}
\makeatletter
\newenvironment{kframe}{%
\def\at@end@of@kframe{}%
\ifinner\ifhmode%
\def\at@end@of@kframe{\end{minipage}}%
\begin{minipage}{\columnwidth}%
\fi\fi%
\def\FrameCommand##1{\hskip\@totalleftmargin \hskip-\fboxsep
\colorbox{shadecolor}{##1}\hskip-\fboxsep
% There is no \\@totalrightmargin, so:
\hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth}%
\MakeFramed {\advance\hsize-\width
\@totalleftmargin\z@ \linewidth\hsize
\@setminipage}}%
{\par\unskip\endMakeFramed%
\at@end@of@kframe}
\makeatother
\definecolor{shadecolor}{rgb}{.97, .97, .97}
\definecolor{messagecolor}{rgb}{0, 0, 0}
\definecolor{warningcolor}{rgb}{1, 0, 1}
\definecolor{errorcolor}{rgb}{1, 0, 0}
\newenvironment{knitrout}{}{} % an empty environment to be redefined in TeX
\usepackage{alltt}
\usepackage{amsthm}
\newtheorem{rexample}{R Example}[section]
\title{Using the Example Environment with knitr}
\author{Yihui Xie}
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
\begin{document}
\maketitle
\section{Introduction}
This is a test of the R Example environment.
\subsection{Go!}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{rexample}\label{test-a}\hfill{}\begin{alltt}
1 + 1
\end{alltt}
\begin{verbatim}
## [1] 2
\end{verbatim}
\end{rexample}\end{kframe}
\end{knitrout}
Look at Example \ref{test-a}!
\subsection{Ha!}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{rexample}\label{test-b}\hfill{}\begin{alltt}
x = \hlfunctioncall{rnorm}(10)
\end{alltt}
\end{rexample}\end{kframe}
\end{knitrout}
Move on!
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{rexample}\label{test-c}\hfill{}\begin{alltt}
\hlfunctioncall{sd}(x) \hlcomment{# standard deviation}
\end{alltt}
\begin{verbatim}
## [1] 0.9538
\end{verbatim}
\end{rexample}\end{kframe}
\end{knitrout}
How about \ref{test-b} and \ref{test-c}?
If you want to use this R Example environment for all code chunks, make rexample a global chunk option in the setup chunk.
\end{document}
\documentclass{article}
\title{Using knit\_expand() for templates}
\author{Yihui Xie}
\begin{document}
\maketitle
\tableofcontents
\section{Write one row of data}
Only the first two sections are evaluated.
<<run-all, include=FALSE>>=
src = NULL
for (i in 1:5) src = c(src, knit_expand('075-template.rnw'))
@
\Sexpr{paste(knit(text = src), collapse = '\n')}
\section{A regression model on several variables}
You can expand a template file, or just provide the template as a character string.
<<lm-mtcars, tidy.opts=list(width.cutoff=55)>>=
# the template
tpl = c("\\subsection{Regression on {{xvar}}}",
"<<lm-{{xvar}}>>=",
"lm(mpg~{{xvar}}, data=mtcars)",
"@")
# expand to knitr source and pass to knit()
src = lapply(names(mtcars)[-1], function(xvar) {knit_expand(text = tpl)})
@
\Sexpr{knit(text = unlist(src))}
\section{Multiple variables}
<<multiple-tpl>>=
tpl = 'The value of a is {{a}} and b is {{b}}.'
@
\Sexpr{knit_expand(text = tpl, a = 1, b = 2)}
\Sexpr{knit_expand(text = tpl, a = 5, b = 2013)}
\end{document}
\documentclass{article}\usepackage[]{graphicx}\usepackage[]{color}
%% maxwidth is the original width if it is less than linewidth
%% otherwise use linewidth (to make sure the graphics do not exceed the margin)
\makeatletter
\def\maxwidth{ %
\ifdim\Gin@nat@width>\linewidth
\linewidth
\else
\Gin@nat@width
\fi
}
\makeatother
\definecolor{fgcolor}{rgb}{0.2, 0.2, 0.2}
\newcommand{\hlnumber}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlfunctioncall}[1]{\textcolor[rgb]{0.501960784313725,0,0.329411764705882}{\textbf{#1}}}%
\newcommand{\hlstring}[1]{\textcolor[rgb]{0.6,0.6,1}{#1}}%
\newcommand{\hlkeyword}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlargument}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlcomment}[1]{\textcolor[rgb]{0.180392156862745,0.6,0.341176470588235}{#1}}%
\newcommand{\hlroxygencomment}[1]{\textcolor[rgb]{0.43921568627451,0.47843137254902,0.701960784313725}{#1}}%
\newcommand{\hlformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hleqformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlassignement}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlpackage}[1]{\textcolor[rgb]{0.588235294117647,0.709803921568627,0.145098039215686}{#1}}%
\newcommand{\hlslot}[1]{\textit{#1}}%
\newcommand{\hlsymbol}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlprompt}[1]{\textcolor[rgb]{0.2,0.2,0.2}{#1}}%
\usepackage{framed}
\makeatletter
\newenvironment{kframe}{%
\def\at@end@of@kframe{}%
\ifinner\ifhmode%
\def\at@end@of@kframe{\end{minipage}}%
\begin{minipage}{\columnwidth}%
\fi\fi%
\def\FrameCommand##1{\hskip\@totalleftmargin \hskip-\fboxsep
\colorbox{shadecolor}{##1}\hskip-\fboxsep
% There is no \\@totalrightmargin, so:
\hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth}%
\MakeFramed {\advance\hsize-\width
\@totalleftmargin\z@ \linewidth\hsize
\@setminipage}}%
{\par\unskip\endMakeFramed%
\at@end@of@kframe}
\makeatother
\definecolor{shadecolor}{rgb}{.97, .97, .97}
\definecolor{messagecolor}{rgb}{0, 0, 0}
\definecolor{warningcolor}{rgb}{1, 0, 1}
\definecolor{errorcolor}{rgb}{1, 0, 0}
\newenvironment{knitrout}{}{} % an empty environment to be redefined in TeX
\usepackage{alltt}
\title{Using knit\_expand() for templates}
\author{Yihui Xie}
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
\begin{document}
\maketitle
\tableofcontents
\section{Write one row of data}
Only the first two sections are evaluated.
\subsection{Now i is 1}
This chunk is evaluated.
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlcomment{# row number 1}
iris[1, ]
\end{alltt}
\begin{verbatim}
## Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1 5.1 3.5 1.4 0.2 setosa
\end{verbatim}
\end{kframe}
\end{knitrout}
\subsection{Now i is 2}
This chunk is evaluated.
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlcomment{# row number 2}
iris[2, ]
\end{alltt}
\begin{verbatim}
## Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 2 4.9 3 1.4 0.2 setosa
\end{verbatim}
\end{kframe}
\end{knitrout}
\subsection{Now i is 3}
This chunk is not evaluated.
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlcomment{# row number 3}
iris[3, ]
\end{alltt}
\end{kframe}
\end{knitrout}
\subsection{Now i is 4}
This chunk is not evaluated.
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlcomment{# row number 4}
iris[4, ]
\end{alltt}
\end{kframe}
\end{knitrout}
\subsection{Now i is 5}
This chunk is not evaluated.
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlcomment{# row number 5}
iris[5, ]
\end{alltt}
\end{kframe}
\end{knitrout}
\section{A regression model on several variables}
You can expand a template file, or just provide the template as a character string.
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlcomment{# the template}
tpl = \hlfunctioncall{c}(\hlstring{"\textbackslash{}\textbackslash{}subsection\{Regression on \{\{xvar\}\}\}"}, \hlstring{"<<lm-\{\{xvar\}\}>>="},
\hlstring{"\hlfunctioncall{lm}(mpg~\{\{xvar\}\}, data=mtcars)"}, \hlstring{"@"})
\hlcomment{# expand to knitr source and pass to knit()}
src = \hlfunctioncall{lapply}(\hlfunctioncall{names}(mtcars)[-1], \hlfunctioncall{function}(xvar) \{
\hlfunctioncall{knit_expand}(text = tpl)
\})
\end{alltt}
\end{kframe}
\end{knitrout}
\subsection{Regression on cyl}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlfunctioncall{lm}(mpg ~ cyl, data = mtcars)
\end{alltt}
\begin{verbatim}
##
## Call:
## lm(formula = mpg ~ cyl, data = mtcars)
##
## Coefficients:
## (Intercept) cyl
## 37.88 -2.88
\end{verbatim}
\end{kframe}
\end{knitrout}
\subsection{Regression on disp}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlfunctioncall{lm}(mpg ~ disp, data = mtcars)
\end{alltt}
\begin{verbatim}
##
## Call:
## lm(formula = mpg ~ disp, data = mtcars)
##
## Coefficients:
## (Intercept) disp
## 29.5999 -0.0412
\end{verbatim}
\end{kframe}
\end{knitrout}
\subsection{Regression on hp}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlfunctioncall{lm}(mpg ~ hp, data = mtcars)
\end{alltt}
\begin{verbatim}
##
## Call:
## lm(formula = mpg ~ hp, data = mtcars)
##
## Coefficients:
## (Intercept) hp
## 30.0989 -0.0682
\end{verbatim}
\end{kframe}
\end{knitrout}
\subsection{Regression on drat}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlfunctioncall{lm}(mpg ~ drat, data = mtcars)
\end{alltt}
\begin{verbatim}
##
## Call:
## lm(formula = mpg ~ drat, data = mtcars)
##
## Coefficients:
## (Intercept) drat
## -7.52 7.68
\end{verbatim}
\end{kframe}
\end{knitrout}
\subsection{Regression on wt}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlfunctioncall{lm}(mpg ~ wt, data = mtcars)
\end{alltt}
\begin{verbatim}
##
## Call:
## lm(formula = mpg ~ wt, data = mtcars)
##
## Coefficients:
## (Intercept) wt
## 37.29 -5.34
\end{verbatim}
\end{kframe}
\end{knitrout}
\subsection{Regression on qsec}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlfunctioncall{lm}(mpg ~ qsec, data = mtcars)
\end{alltt}
\begin{verbatim}
##
## Call:
## lm(formula = mpg ~ qsec, data = mtcars)
##
## Coefficients:
## (Intercept) qsec
## -5.11 1.41
\end{verbatim}
\end{kframe}
\end{knitrout}
\subsection{Regression on vs}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlfunctioncall{lm}(mpg ~ vs, data = mtcars)
\end{alltt}
\begin{verbatim}
##
## Call:
## lm(formula = mpg ~ vs, data = mtcars)
##
## Coefficients:
## (Intercept) vs
## 16.62 7.94
\end{verbatim}
\end{kframe}
\end{knitrout}
\subsection{Regression on am}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlfunctioncall{lm}(mpg ~ am, data = mtcars)
\end{alltt}
\begin{verbatim}
##
## Call:
## lm(formula = mpg ~ am, data = mtcars)
##
## Coefficients:
## (Intercept) am
## 17.15 7.24
\end{verbatim}
\end{kframe}
\end{knitrout}
\subsection{Regression on gear}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlfunctioncall{lm}(mpg ~ gear, data = mtcars)
\end{alltt}
\begin{verbatim}
##
## Call:
## lm(formula = mpg ~ gear, data = mtcars)
##
## Coefficients:
## (Intercept) gear
## 5.62 3.92
\end{verbatim}
\end{kframe}
\end{knitrout}
\subsection{Regression on carb}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlfunctioncall{lm}(mpg ~ carb, data = mtcars)
\end{alltt}
\begin{verbatim}
##
## Call:
## lm(formula = mpg ~ carb, data = mtcars)
##
## Coefficients:
## (Intercept) carb
## 25.87 -2.06
\end{verbatim}
\end{kframe}
\end{knitrout}
\section{Multiple variables}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
tpl = \hlstring{"The value of a is \{\{a\}\} and b is \{\{b\}\}."}
\end{alltt}
\end{kframe}
\end{knitrout}
The value of a is 1 and b is 2.
The value of a is 5 and b is 2013.
\end{document}
\subsection{Now i is {{i}}}
This chunk is {{if (i > 2) 'not '}}evaluated.
<<row-{{i}}, eval={{i <= 2}}>>=
# row number {{i}}
iris[{{i}}, ]
@
\documentclass{ctexart}
\begin{document}
中文测试。
<<test, tidy=FALSE>>=
# 中文哈哈
1+1 # 行内注释
'还是我'
@
\Sexpr{'仍然是'}中文,然后这里有\Sexpr{rep('很多',10)}中文。
<<test>>=
@
本文档编码为GBK。
\end{document}
\documentclass{ctexart}\usepackage[]{graphicx}\usepackage[]{color}
%% maxwidth is the original width if it is less than linewidth
%% otherwise use linewidth (to make sure the graphics do not exceed the margin)
\makeatletter
\def\maxwidth{ %
\ifdim\Gin@nat@width>\linewidth
\linewidth
\else
\Gin@nat@width
\fi
}
\makeatother
\definecolor{fgcolor}{rgb}{0.2, 0.2, 0.2}
\newcommand{\hlnumber}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlfunctioncall}[1]{\textcolor[rgb]{0.501960784313725,0,0.329411764705882}{\textbf{#1}}}%
\newcommand{\hlstring}[1]{\textcolor[rgb]{0.6,0.6,1}{#1}}%
\newcommand{\hlkeyword}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlargument}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlcomment}[1]{\textcolor[rgb]{0.180392156862745,0.6,0.341176470588235}{#1}}%
\newcommand{\hlroxygencomment}[1]{\textcolor[rgb]{0.43921568627451,0.47843137254902,0.701960784313725}{#1}}%
\newcommand{\hlformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hleqformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlassignement}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlpackage}[1]{\textcolor[rgb]{0.588235294117647,0.709803921568627,0.145098039215686}{#1}}%
\newcommand{\hlslot}[1]{\textit{#1}}%
\newcommand{\hlsymbol}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlprompt}[1]{\textcolor[rgb]{0.2,0.2,0.2}{#1}}%
\usepackage{framed}
\makeatletter
\newenvironment{kframe}{%
\def\at@end@of@kframe{}%
\ifinner\ifhmode%
\def\at@end@of@kframe{\end{minipage}}%
\begin{minipage}{\columnwidth}%
\fi\fi%
\def\FrameCommand##1{\hskip\@totalleftmargin \hskip-\fboxsep
\colorbox{shadecolor}{##1}\hskip-\fboxsep
% There is no \\@totalrightmargin, so:
\hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth}%
\MakeFramed {\advance\hsize-\width
\@totalleftmargin\z@ \linewidth\hsize
\@setminipage}}%
{\par\unskip\endMakeFramed%
\at@end@of@kframe}
\makeatother
\definecolor{shadecolor}{rgb}{.97, .97, .97}
\definecolor{messagecolor}{rgb}{0, 0, 0}
\definecolor{warningcolor}{rgb}{1, 0, 1}
\definecolor{errorcolor}{rgb}{1, 0, 0}
\newenvironment{knitrout}{}{} % an empty environment to be redefined in TeX
\usepackage{alltt}
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
\begin{document}
中文测试。
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlcomment{# 中文哈哈}
1+1 \hlcomment{# 行内注释}
\end{alltt}
\begin{verbatim}
## [1] 2
\end{verbatim}
\begin{alltt}
\hlstring{'还是我'}
\end{alltt}
\begin{verbatim}
## [1] "还是我"
\end{verbatim}
\end{kframe}
\end{knitrout}
仍然是中文,然后这里有很多, 很多, 很多, 很多, 很多, 很多, 很多, 很多, 很多, 很多中文。
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlcomment{# 中文哈哈}
1 + 1 \hlcomment{# 行内注释}
\end{alltt}
\begin{verbatim}
## [1] 2
\end{verbatim}
\begin{alltt}
\hlstring{"还是我"}
\end{alltt}
\begin{verbatim}
## [1] "还是我"
\end{verbatim}
\end{kframe}
\end{knitrout}
本文档编码为GBK。
\end{document}

Wrap long lines

Long lines in the output will not be (hard-)wrapped automatically unless you break them manually.

a <- "## \"stx2A; shiga-like toxin II A subunit encoded by bacteriophage BP-933W; K11006 shiga toxin subunit A\" "
a
## [1] "## \"stx2A; shiga-like toxin II A subunit encoded by bacteriophage BP-933W; K11006 shiga toxin subunit A\" "

Perhaps you see it is wrapped in RStudio, but that is because <pre> has the CSS attribute white-space: pre-wrap;. For LaTeX output, the output is in the verbatim environment by default, which will not wrap long lines (everything is shown as is).

You can redefine the output hook function so that you can instruct some chunks to hard-wrap their output lines, e.g.

hook_output = knit_hooks$get("output")
knit_hooks$set(output = function(x, options) {
    # this hook is used only when the linewidth option is not NULL
    if (!is.null(n <- options$linewidth)) {
        x = knitr:::split_lines(x)
        # any lines wider than n should be wrapped
        if (any(nchar(x) > n)) 
            x = strwrap(x, width = n)
        x = paste(x, collapse = "\n")
    }
    hook_output(x, options)
})

Now see the output of a (note linewidth is not a default knitr option):

a
## [1] "## \"stx2A; shiga-like toxin II A subunit encoded
by bacteriophage BP-933W; K11006 shiga toxin subunit A\" "
# Wrap long lines
Long lines in the output will not be (hard-)wrapped automatically unless you break them manually.
```{r long_output}
a <- '## "stx2A; shiga-like toxin II A subunit encoded by bacteriophage BP-933W; K11006 shiga toxin subunit A" '
a
```
Perhaps you see it is wrapped in RStudio, but that is because `<pre>` has the CSS attribute `white-space: pre-wrap;`. For LaTeX output, the output is in the `verbatim` environment by default, which will not wrap long lines (everything is shown as is).
You can redefine the output hook function so that you can instruct some chunks to hard-wrap their output lines, e.g.
```{r wrap-hook}
hook_output = knit_hooks$get('output')
knit_hooks$set(output = function(x, options) {
# this hook is used only when the linewidth option is not NULL
if (!is.null(n <- options$linewidth)) {
x = knitr:::split_lines(x)
# any lines wider than n should be wrapped
if (any(nchar(x) > n)) x = strwrap(x, width = n)
x = paste(x, collapse = '\n')
}
hook_output(x, options)
})
```
Now see the output of `a` (note `linewidth` is not a default **knitr** option):
```{r test, linewidth=60}
a
```
% 據說Cwtex可以編譯,但我沒有試過
\documentclass{article}\usepackage[]{graphicx}\usepackage[]{color}
%% maxwidth is the original width if it is less than linewidth
%% otherwise use linewidth (to make sure the graphics do not exceed the margin)
\makeatletter
\def\maxwidth{ %
\ifdim\Gin@nat@width>\linewidth
\linewidth
\else
\Gin@nat@width
\fi
}
\makeatother
\definecolor{fgcolor}{rgb}{0.2, 0.2, 0.2}
\newcommand{\hlnumber}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlfunctioncall}[1]{\textcolor[rgb]{0.501960784313725,0,0.329411764705882}{\textbf{#1}}}%
\newcommand{\hlstring}[1]{\textcolor[rgb]{0.6,0.6,1}{#1}}%
\newcommand{\hlkeyword}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlargument}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlcomment}[1]{\textcolor[rgb]{0.180392156862745,0.6,0.341176470588235}{#1}}%
\newcommand{\hlroxygencomment}[1]{\textcolor[rgb]{0.43921568627451,0.47843137254902,0.701960784313725}{#1}}%
\newcommand{\hlformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hleqformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlassignement}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlpackage}[1]{\textcolor[rgb]{0.588235294117647,0.709803921568627,0.145098039215686}{#1}}%
\newcommand{\hlslot}[1]{\textit{#1}}%
\newcommand{\hlsymbol}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlprompt}[1]{\textcolor[rgb]{0.2,0.2,0.2}{#1}}%
\usepackage{framed}
\makeatletter
\newenvironment{kframe}{%
\def\at@end@of@kframe{}%
\ifinner\ifhmode%
\def\at@end@of@kframe{\end{minipage}}%
\begin{minipage}{\columnwidth}%
\fi\fi%
\def\FrameCommand##1{\hskip\@totalleftmargin \hskip-\fboxsep
\colorbox{shadecolor}{##1}\hskip-\fboxsep
% There is no \\@totalrightmargin, so:
\hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth}%
\MakeFramed {\advance\hsize-\width
\@totalleftmargin\z@ \linewidth\hsize
\@setminipage}}%
{\par\unskip\endMakeFramed%
\at@end@of@kframe}
\makeatother
\definecolor{shadecolor}{rgb}{.97, .97, .97}
\definecolor{messagecolor}{rgb}{0, 0, 0}
\definecolor{warningcolor}{rgb}{1, 0, 1}
\definecolor{errorcolor}{rgb}{1, 0, 0}
\newenvironment{knitrout}{}{} % an empty environment to be redefined in TeX
\usepackage{alltt}
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
\begin{document}
\title{knitr與繁體中文文檔}
\author{謝益輝}
測試,咳咳。以下代碼靠譜嗎?
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
1 + 1 \hlcomment{# 太簡單了}
\end{alltt}
\begin{verbatim}
## [1] 2
\end{verbatim}
\begin{alltt}
\hlstring{"引號能用嗎?"}
\end{alltt}
\begin{verbatim}
## [1] "引號能用嗎?"
\end{verbatim}
\begin{alltt}
\hlfunctioncall{rnorm}(5)
\end{alltt}
\begin{verbatim}
## [1] -0.56048 -0.23018 1.55871 0.07051 0.12929
\end{verbatim}
\begin{alltt}
(\hlfunctioncall{function}() \{
\hlfunctioncall{paste}(\hlstring{"這裡是字符串"})
\})()
\end{alltt}
\begin{verbatim}
## [1] "這裡是字符串"
\end{verbatim}
\end{kframe}
\end{knitrout}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
1+1 \hlcomment{# 太簡單了}
\end{alltt}
\begin{verbatim}
## [1] 2
\end{verbatim}
\begin{alltt}
\hlstring{'引號能用嗎?'}
\end{alltt}
\begin{verbatim}
## [1] "引號能用嗎?"
\end{verbatim}
\begin{alltt}
\hlfunctioncall{rnorm}(5)
\end{alltt}
\begin{verbatim}
## [1] 1.7151 0.4609 -1.2651 -0.6869 -0.4457
\end{verbatim}
\begin{alltt}
(\hlfunctioncall{function}()\{
\hlfunctioncall{paste}(\hlstring{'這裡是字符串'})
\})()
\end{alltt}
\begin{verbatim}
## [1] "這裡是字符串"
\end{verbatim}
\end{kframe}
\end{knitrout}
正文中可以出現中文代碼嗎?
至少編碼是BIG5沒有問題。
\end{document}
% 據說Cwtex可以編譯,但我沒有試過
\documentclass{article}
\begin{document}
\title{knitr與繁體中文文檔}
\author{謝益輝}
測試,咳咳。以下代碼靠譜嗎?
<<test>>=
1+1 # 太簡單了
'引號能用嗎?'
rnorm(5)
(function(){
paste('這裡是字符串')
})()
@
<<test, tidy=FALSE>>=
@
正文中可以出現\Sexpr{if (TRUE) '中文代碼'}嗎?
至少編碼是BIG5沒有問題。
\end{document}

Evaluate and echo different lines

For demonstration purposes, we may want to show some source code in the output, but really evaluate different code in the background.

hook_source = knit_hooks$get("source")
knit_hooks$set(source = function(x, options) {
    res = hook_source(x, options)
    if (!grepl("#'#' ", x)) 
        return(res)
    gsub("(^|\n)#'#' ", "\\1", res)
})

The trick is to mask the source code in special comments (e.g. #'#'), and remove the comment markers later. Of course, you have to guarantee these markers are unique.

x = 2
1/sqrt(2 * pi) * exp(-x^2/2)
## [1] 0.05399

We used echo=-3 to remove the 3rd expression from the source code, and gsub() to strip #'#' off.

This is completely hack. Use with care.

# Evaluate and echo different lines
For demonstration purposes, we may want to show some source code in the output, but really evaluate different code in the background.
```{r}
hook_source = knit_hooks$get('source')
knit_hooks$set(source = function(x, options) {
res = hook_source(x, options)
if (!grepl("#'#' ", x)) return(res)
gsub("(^|\n)#'#' ", '\\1', res)
})
```
The trick is to mask the source code in special comments (e.g. `#'#'`), and remove the comment markers later. Of course, you have to guarantee these markers are unique.
```{r test, echo=-3}
x=2
#'#' 1/sqrt(2 * pi) * exp(-x^2/2)
dnorm(x)
```
We used `echo=-3` to remove the 3rd expression from the source code, and `gsub()` to strip `#'#'` off.
This is completely hack. Use with care.

Using CoffeeScript with knitr

You need to install coffee, the command-line version of CoffeeScript.

CoffeeScript compiles javascript:

@square = (x) -> x * x
// (function() {
// 
//   this.square = function(x) {
//     return x * x;
//   };
// 
// }).call(this);

To use CoffeeScript in an HTML document, use results="asis", echo=FALSE, and wrap the chunk in <script> tags.

@square = (x) -> x * x
@cube   = (x) -> square(x) * x
p = document.createElement("p");
p.appendChild(document.createTextNode("The cube of 3 is " + cube(3)))
document.body.appendChild(p)
<script type="text/javascript"> (function() { this.square = function(x) { return x * x; }; this.cube = function(x) { return square(x) * x; }; }).call(this); (function() { var p; p = document.createElement("p"); p.appendChild(document.createTextNode("The cube of 3 is " + cube(3))); document.body.appendChild(p); }).call(this); </script>
# Using CoffeeScript with knitr
You need to install `coffee`, the command-line version of [CoffeeScript](http://coffeescript.org/#installation).
CoffeeScript compiles javascript:
```{r square_function, engine="coffee", comment='//'}
@square = (x) -> x * x
```
To use CoffeeScript in an HTML document, use `results="asis"`, `echo=FALSE`, and wrap the chunk in `<script>` tags.
```{r ref.label="math_functions", engine="coffee", eval=FALSE}
```
```{r ref.label="call_math", engine="coffee", eval=FALSE}
```
<script type="text/javascript">
```{r math_functions, engine="coffee", results="asis", echo=FALSE}
@square = (x) -> x * x
@cube = (x) -> square(x) * x
```
```{r call_math, engine="coffee", results="asis", echo=FALSE}
p = document.createElement("p");
p.appendChild(document.createTextNode("The cube of 3 is " + cube(3)))
document.body.appendChild(p)
```
</script>
#LyX 2.0 created this file. For more info see http://www.lyx.org/
\lyxformat 413
\begin_document
\begin_header
\textclass ctex-article
\begin_preamble
\DeclareRobustCommand\nobreakspace{\leavevmode\nobreak\ }
\end_preamble
\options UTF8,adobefonts
\use_default_options true
\begin_modules
knitr
\end_modules
\maintain_unincluded_children false
\language chinese-simplified
\language_package none
\inputencoding utf8-plain
\fontencoding global
\font_roman default
\font_sans default
\font_typewriter default
\font_default_family default
\use_non_tex_fonts false
\font_sc false
\font_osf false
\font_sf_scale 100
\font_tt_scale 100
\graphics default
\default_output_format pdf4
\output_sync 0
\bibtex_command default
\index_command default
\paperfontsize default
\spacing single
\use_hyperref false
\papersize default
\use_geometry false
\use_amsmath 1
\use_esint 1
\use_mhchem 1
\use_mathdots 1
\cite_engine basic
\use_bibtopic false
\use_indices false
\paperorientation portrait
\suppress_date false
\use_refstyle 1
\index Index
\shortcut idx
\color #008000
\end_index
\secnumdepth 3
\tocdepth 3
\paragraph_separation indent
\paragraph_indentation default
\quotes_language english
\papercolumns 1
\papersides 1
\paperpagestyle default
\tracking_changes false
\output_changes false
\html_math_output 0
\html_css_as_file 0
\html_be_strict false
\end_header
\begin_body
\begin_layout Title
妈妈说中文报告也可以用knitr自动生成
\end_layout
\begin_layout Author
谢益辉
\end_layout
\begin_layout Standard
该说的都在这个页面
\begin_inset Flex URL
status collapsed
\begin_layout Plain Layout
http://yihui.name/knitr/demo/lyx/
\end_layout
\end_inset
里面说了。先写个“你好世界”:
\end_layout
\begin_layout Standard
\begin_inset ERT
status open
\begin_layout Plain Layout
<<hello-world>>=
\end_layout
\begin_layout Plain Layout
options(digits=3)
\end_layout
\begin_layout Plain Layout
x=1+1 # 测试注释
\end_layout
\begin_layout Plain Layout
'字符串引号在Windows下很痛苦,Linux表示压力不大'
\end_layout
\begin_layout Plain Layout
@
\end_layout
\end_inset
\end_layout
\begin_layout Standard
图形如何?
\end_layout
\begin_layout Standard
\begin_inset ERT
status open
\begin_layout Plain Layout
<<test-plot, fig.width=5, fig.height=3.5, out.width='.7
\backslash
\backslash
textwidth', fig.align='center'>>=
\end_layout
\begin_layout Plain Layout
par(mar=c(4, 4, .2, .1), las=1)
\end_layout
\begin_layout Plain Layout
smoothScatter(cars)
\end_layout
\begin_layout Plain Layout
@
\end_layout
\end_inset
\end_layout
\begin_layout Standard
表格又如何?
\end_layout
\begin_layout Standard
\begin_inset ERT
status open
\begin_layout Plain Layout
<<test-table, results='asis'>>=
\end_layout
\begin_layout Plain Layout
library(xtable)
\end_layout
\begin_layout Plain Layout
xtable(head(iris), caption='你好啊标题!')
\end_layout
\begin_layout Plain Layout
@
\end_layout
\end_inset
\end_layout
\begin_layout Standard
汇报完毕。
\end_layout
\end_body
\end_document
\documentclass{article}
\usepackage[x11names]{xcolor}
\DefineVerbatimEnvironment{Sinput}{Verbatim}{formatcom=\color{Blue3}}
\DefineVerbatimEnvironment{Soutput}{Verbatim}{formatcom=\color{gray}}
\begin{document}
<<setup, include=FALSE>>=
render_sweave()
@
Test. Source code is {\color{Blue3}Blue3}, and output is {\color{gray}gray}.
<<>>=
1+1
rnorm(5)
@
\end{document}
\documentclass{article}\usepackage[]{graphicx}\usepackage[]{color}
%% maxwidth is the original width if it is less than linewidth
%% otherwise use linewidth (to make sure the graphics do not exceed the margin)
\makeatletter
\def\maxwidth{ %
\ifdim\Gin@nat@width>\linewidth
\linewidth
\else
\Gin@nat@width
\fi
}
\makeatother
\usepackage{Sweave}
\usepackage[x11names]{xcolor}
\DefineVerbatimEnvironment{Sinput}{Verbatim}{formatcom=\color{Blue3}}
\DefineVerbatimEnvironment{Soutput}{Verbatim}{formatcom=\color{gray}}
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
\begin{document}
Test. Source code is {\color{Blue3}Blue3}, and output is {\color{gray}gray}.
\begin{Schunk}
\begin{Sinput}
> 1 + 1
\end{Sinput}
\begin{Soutput}
[1] 2
\end{Soutput}
\begin{Sinput}
> rnorm(5)
\end{Sinput}
\begin{Soutput}
[1] -0.56048 -0.23018 1.55871 0.07051 0.12929
\end{Soutput}
\end{Schunk}
\end{document}

Externalize ggplot2 code

You may have your own layout code like this one, and you do not want to type the code again and again. One way to avoid repeating the code explicitly is to use chunk references. Although knitr is based on the idea of literate programming, but we rarely need programming, and this is one case in which literate programming may be helpful.

We simplify the layout code in the original post and put it in a code chunk named my-layout:

theme(legend.text = element_text(size = 12, angle = 45)) + theme(legend.position = "bottom")

Now we can use <<>> to reference it.

library(ggplot2)
## Loading required package: methods
qplot(carat, price, data = diamonds, color = cut) + theme(legend.text = element_text(size = 12, 
    angle = 45)) + theme(legend.position = "bottom")

plot of chunk test-a

Another test:

qplot(carat, data = diamonds, fill = cut) + theme(legend.text = element_text(size = 12, 
    angle = 45)) + theme(legend.position = "bottom")
## stat_bin: binwidth defaulted to range/30. Use 'binwidth = x' to adjust
## this.

plot of chunk test-b

# Externalize ggplot2 code
You may have your own layout code like [this one](http://stackoverflow.com/q/14802183/559676), and you do not want to type the code again and again. One way to avoid repeating the code explicitly is to use chunk references. Although **knitr** is based on the idea of literate programming, but we rarely need programming, and this is one case in which literate programming may be helpful.
We simplify the layout code in the original post and put it in a code chunk named `my-layout`:
```{r my-layout, eval=FALSE}
theme (legend.text = element_text(size = 12, angle=45))+
theme (legend.position = "bottom")
```
Now we can use `<<>>` to reference it.
```{r test-a}
library(ggplot2)
qplot(carat, price, data=diamonds, color=cut)+
<<my-layout>>
```
Another test:
```{r test-b}
qplot(carat, data=diamonds, fill=cut)+
<<my-layout>>
```
@Manual{R-base,
title = {R: A Language and Environment for Statistical Computing},
author = {{R Core Team}},
organization = {R Foundation for Statistical Computing},
address = {Vienna, Austria},
year = {2013},
note = {{ISBN} 3-900051-07-0},
url = {http://www.R-project.org/},
}
@book{xie2013,
title={Dynamic Documents with R and knitr},
author={Yihui Xie},
year={2013},
note={{ISBN} 9781482203530},
publisher={Chapman \& Hall/CRC}
}

% Converting Markdown to Other Formats with knitr::pandoc() % Yihui Xie % March 1st, 2013

A bit introduction here.

Start with a cool section

You can use traditional Markdown syntax, such as links and code.

Followed by another section

Of course you can write lists:

  • apple
  • pear
  • banana

Or ordered lists:

  1. items
  2. will
  3. be
  4. ordered
    • nested
    • items

More sections

Hi

hi hi

Hello

hello hello

Howdy

howdy howdy

Okay, some R code

fit = lm(dist ~ speed, data = cars)
b = coef(fit)  # coefficients
summary(fit)
## 
## Call:
## lm(formula = dist ~ speed, data = cars)
## 
## Residuals:
##    Min     1Q Median     3Q    Max 
## -29.07  -9.53  -2.27   9.21  43.20 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept)  -17.579      6.758   -2.60    0.012 *  
## speed          3.932      0.416    9.46  1.5e-12 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 15.4 on 48 degrees of freedom
## Multiple R-squared:  0.651,	Adjusted R-squared:  0.644 
## F-statistic: 89.6 on 1 and 48 DF,  p-value: 1.49e-12

The code will be highlighted in all output formats.

And some pictures

par(mfrow = c(2, 2), pch = 20, mar = c(4, 4, 2, 0.1), bg = "white")
plot(fit)

Regression diagnostics

A little bit math

Our regression equation is $Y=-17.5791+3.9324x$, and the model is:

$$ Y = \beta_0 + \beta_1 x + \epsilon$$

Pandoc extension: definition lists

Programmer : A programmer is the one who turns coffee into code. LaTeX : A simple tool which is nothing but a couple of backslashes.

Pandoc extension: examples

We have some examples.

(@) Think what is 0.3 + 0.4 - 0.7. Zero. Easy. (@weird) Now think what is 0.3 - 0.7 + 0.4. Still zero?

People are often surprised by (@weird).

Pandoc extension: tables

A table here.

Table: Demonstration of simple table syntax.

Right Left Center Default


 12     12        12            12
123     123       123          123
  1     1          1             1

Pandoc extension: footnotes

We can also write footnotes1.

Or write some inline footnotes^[as you can see here].

Pandoc extension: citations

We compile the R Markdown file to Markdown through knitr [@xie2013] in R [@R-base]. For more about @xie2013, see http://yihui.name/knitr.

References

Footnotes

  1. hi, I'm a footnote

bibliography: 084-pandoc.bib
084-pandoc-more.bib
standalone:
toc:
format: latex
latex-engine: xelatex
number-sections:
output: 084-pandoc-xelatex.pdf
format: beamer
latex-engine: pdflatex
incremental:
output: 084-pandoc-beamer.pdf
format: html
mathjax:
number-sections:
format: dzslides
mathjax:
number-sections:
output: 084-pandoc-slides.html
library(knitr)
# this feature comes in v1.2
stopifnot(packageVersion('knitr') > '1.1')
knit('084-pandoc.Rmd')
# default is HTML output
pandoc('084-pandoc.md')
# there are sections of arguments specified in 084-pandoc.pandoc, e.g. dzslides,
# but note that the output name is 084-pandoc-slides.html, and the default name
# would be 084-pandoc.html
pandoc('084-pandoc.md', format = 'dzslides')
# it is also possible to convert md to pdf through xelatex
pandoc('084-pandoc.md', format = 'latex')
# the default latex engine is pdflatex; to use pdflatex, just remove
# `latex-engine: xelatex` from the configuration file
# convert to beamer slides
pandoc('084-pandoc.md', format = 'beamer')
# the configuration file 084-pandoc.pandoc did not specify other formats such as
# docx or odt, epub, etc, and pandoc() will only pass the common settings in the
# first section of the configuration file
pandoc('084-pandoc.md', format = 'docx')
pandoc('084-pandoc.md', format = 'odt')
pandoc('084-pandoc.md', format = 'epub')
# you might have noticed that the plot looks blurred in LaTeX/PDF output and
# that is because R Markdown uses the png() device by default; we can certainly
# use pdf()
if (FALSE) {
render_markdown()
opts_chunk$set(dev = 'pdf')
knit('084-pandoc.Rmd')
# now it should be better
pandoc('084-pandoc.md', format = 'latex')
}
% Converting Markdown to Other Formats with knitr::pandoc()
% [Yihui Xie](http://yihui.name)
% March 1st, 2013
A bit _introduction_ here.
# Start with a cool section
You can use traditional **Markdown** syntax, such as [links](http://yihui.name/knitr) and `code`.
# Followed by another section
Of course you can write lists:
- apple
- pear
- banana
Or ordered lists:
1. items
1. will
1. be
1. ordered
- nested
- items
# More sections
## Hi
hi hi
## Hello
hello hello
## Howdy
howdy howdy
# Okay, some R code
```{r linear-model}
fit = lm(dist ~ speed, data = cars)
b = coef(fit) # coefficients
summary(fit)
```
The code will be highlighted in all output formats.
# And some pictures
```{r lm-vis, fig.cap='Regression diagnostics'}
par(mfrow = c(2, 2), pch = 20, mar = c(4, 4, 2, .1), bg = 'white')
plot(fit)
```
# A little bit math
Our regression equation is $Y=`r b[1]`+`r b[2]`x$, and the model is:
$$ Y = \beta_0 + \beta_1 x + \epsilon$$
# Pandoc extension: definition lists
Programmer
: A programmer is the one who turns coffee into code.
LaTeX
: A simple tool which is nothing but a couple of backslashes.
# Pandoc extension: examples
We have some examples.
(@) Think what is `0.3 + 0.4 - 0.7`. Zero. Easy.
(@weird) Now think what is `0.3 - 0.7 + 0.4`. Still zero?
People are often surprised by (@weird).
# Pandoc extension: tables
A table here.
Table: Demonstration of simple table syntax.
Right Left Center Default
------- ------ ---------- -------
12 12 12 12
123 123 123 123
1 1 1 1
# Pandoc extension: footnotes
We can also write footnotes[^1].
[^1]: hi, I'm a footnote
Or write some inline footnotes^[as you can see here].
# Pandoc extension: citations
We compile the R Markdown file to Markdown through **knitr** [@xie2013] in R [@R-base]. For more about @xie2013, see <http://yihui.name/knitr>.
# References
\documentclass{article}
\begin{document}
<<setup, include=FALSE>>=
knit_hooks$set(crop = hook_pdfcrop)
@
Cropped.
<<test-a, crop=TRUE, fig.width=3, fig.height=3, cache=TRUE>>=
plot(1)
@
Not cropped.
<<test-b, fig.width=3, fig.height=3>>=
plot(1)
@
\end{document}
\documentclass{article}\usepackage[]{graphicx}\usepackage[]{color}
%% maxwidth is the original width if it is less than linewidth
%% otherwise use linewidth (to make sure the graphics do not exceed the margin)
\makeatletter
\def\maxwidth{ %
\ifdim\Gin@nat@width>\linewidth
\linewidth
\else
\Gin@nat@width
\fi
}
\makeatother
\definecolor{fgcolor}{rgb}{0.2, 0.2, 0.2}
\newcommand{\hlnumber}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlfunctioncall}[1]{\textcolor[rgb]{0.501960784313725,0,0.329411764705882}{\textbf{#1}}}%
\newcommand{\hlstring}[1]{\textcolor[rgb]{0.6,0.6,1}{#1}}%
\newcommand{\hlkeyword}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlargument}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlcomment}[1]{\textcolor[rgb]{0.180392156862745,0.6,0.341176470588235}{#1}}%
\newcommand{\hlroxygencomment}[1]{\textcolor[rgb]{0.43921568627451,0.47843137254902,0.701960784313725}{#1}}%
\newcommand{\hlformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hleqformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlassignement}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlpackage}[1]{\textcolor[rgb]{0.588235294117647,0.709803921568627,0.145098039215686}{#1}}%
\newcommand{\hlslot}[1]{\textit{#1}}%
\newcommand{\hlsymbol}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlprompt}[1]{\textcolor[rgb]{0.2,0.2,0.2}{#1}}%
\usepackage{framed}
\makeatletter
\newenvironment{kframe}{%
\def\at@end@of@kframe{}%
\ifinner\ifhmode%
\def\at@end@of@kframe{\end{minipage}}%
\begin{minipage}{\columnwidth}%
\fi\fi%
\def\FrameCommand##1{\hskip\@totalleftmargin \hskip-\fboxsep
\colorbox{shadecolor}{##1}\hskip-\fboxsep
% There is no \\@totalrightmargin, so:
\hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth}%
\MakeFramed {\advance\hsize-\width
\@totalleftmargin\z@ \linewidth\hsize
\@setminipage}}%
{\par\unskip\endMakeFramed%
\at@end@of@kframe}
\makeatother
\definecolor{shadecolor}{rgb}{.97, .97, .97}
\definecolor{messagecolor}{rgb}{0, 0, 0}
\definecolor{warningcolor}{rgb}{1, 0, 1}
\definecolor{errorcolor}{rgb}{1, 0, 0}
\newenvironment{knitrout}{}{} % an empty environment to be redefined in TeX
\usepackage{alltt}
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
\begin{document}
Cropped.
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlfunctioncall{plot}(1)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/085-pdfcrop-test-a}
\end{knitrout}
Not cropped.
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlfunctioncall{plot}(1)
\end{alltt}
\end{kframe}
\includegraphics[width=\maxwidth]{figure/085-pdfcrop-test-b}
\end{knitrout}
\end{document}
\documentclass{article}
\begin{document}
<<setup, include=FALSE>>=
options(xtable.comment = FALSE)
@
\section*{Multiplication table}
<<multiplication-table, echo = FALSE, results = 'asis'>>=
library(xtable)
mt <- outer(1:9, 1:9, function(x, y) x *y)
xtable(mt, align="|c|ccccccccc|")
@
\section*{Embedded \LaTeX}
<<embedded-latex, echo = FALSE, results = 'asis'>>=
el <- matrix(rep(1, 9), ncol=3)
colnames(el) <- rownames(el) <- c("$\\alpha$", "$\\beta$", "$\\gamma$")
el[1,1] <- "$\\alpha^2$"
el[2,2] <- "$\\beta^2$"
el[3,3] <- "$\\gamma^2$"
el[1,2] <- el[2,1] <- "$\\alpha\\beta$"
el[1,3] <- el[3,1] <- "$\\alpha\\gamma$"
el[2,3] <- el[3,2] <- "$\\beta\\gamma$"
print(xtable(el), sanitize.text.function = function(x){x})
@
\section*{Names}
<<names, echo = FALSE, results = 'asis'>>=
print(xtable(head(iris)), include.rownames=FALSE)
@
\end{document}
\documentclass{article}\usepackage[]{graphicx}\usepackage[]{color}
%% maxwidth is the original width if it is less than linewidth
%% otherwise use linewidth (to make sure the graphics do not exceed the margin)
\makeatletter
\def\maxwidth{ %
\ifdim\Gin@nat@width>\linewidth
\linewidth
\else
\Gin@nat@width
\fi
}
\makeatother
\definecolor{fgcolor}{rgb}{0.2, 0.2, 0.2}
\newcommand{\hlnumber}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlfunctioncall}[1]{\textcolor[rgb]{0.501960784313725,0,0.329411764705882}{\textbf{#1}}}%
\newcommand{\hlstring}[1]{\textcolor[rgb]{0.6,0.6,1}{#1}}%
\newcommand{\hlkeyword}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlargument}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlcomment}[1]{\textcolor[rgb]{0.180392156862745,0.6,0.341176470588235}{#1}}%
\newcommand{\hlroxygencomment}[1]{\textcolor[rgb]{0.43921568627451,0.47843137254902,0.701960784313725}{#1}}%
\newcommand{\hlformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hleqformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlassignement}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlpackage}[1]{\textcolor[rgb]{0.588235294117647,0.709803921568627,0.145098039215686}{#1}}%
\newcommand{\hlslot}[1]{\textit{#1}}%
\newcommand{\hlsymbol}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlprompt}[1]{\textcolor[rgb]{0.2,0.2,0.2}{#1}}%
\usepackage{framed}
\makeatletter
\newenvironment{kframe}{%
\def\at@end@of@kframe{}%
\ifinner\ifhmode%
\def\at@end@of@kframe{\end{minipage}}%
\begin{minipage}{\columnwidth}%
\fi\fi%
\def\FrameCommand##1{\hskip\@totalleftmargin \hskip-\fboxsep
\colorbox{shadecolor}{##1}\hskip-\fboxsep
% There is no \\@totalrightmargin, so:
\hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth}%
\MakeFramed {\advance\hsize-\width
\@totalleftmargin\z@ \linewidth\hsize
\@setminipage}}%
{\par\unskip\endMakeFramed%
\at@end@of@kframe}
\makeatother
\definecolor{shadecolor}{rgb}{.97, .97, .97}
\definecolor{messagecolor}{rgb}{0, 0, 0}
\definecolor{warningcolor}{rgb}{1, 0, 1}
\definecolor{errorcolor}{rgb}{1, 0, 0}
\newenvironment{knitrout}{}{} % an empty environment to be redefined in TeX
\usepackage{alltt}
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
\begin{document}
\section*{Multiplication table}
\begin{table}[ht]
\centering
\begin{tabular}{|c|ccccccccc|}
\hline
& 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 \\
\hline
1 & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 \\
2 & 2 & 4 & 6 & 8 & 10 & 12 & 14 & 16 & 18 \\
3 & 3 & 6 & 9 & 12 & 15 & 18 & 21 & 24 & 27 \\
4 & 4 & 8 & 12 & 16 & 20 & 24 & 28 & 32 & 36 \\
5 & 5 & 10 & 15 & 20 & 25 & 30 & 35 & 40 & 45 \\
6 & 6 & 12 & 18 & 24 & 30 & 36 & 42 & 48 & 54 \\
7 & 7 & 14 & 21 & 28 & 35 & 42 & 49 & 56 & 63 \\
8 & 8 & 16 & 24 & 32 & 40 & 48 & 56 & 64 & 72 \\
9 & 9 & 18 & 27 & 36 & 45 & 54 & 63 & 72 & 81 \\
\hline
\end{tabular}
\end{table}
\section*{Embedded \LaTeX}
\begin{table}[ht]
\centering
\begin{tabular}{rlll}
\hline
& $\alpha$ & $\beta$ & $\gamma$ \\
\hline
$\alpha$ & $\alpha^2$ & $\alpha\beta$ & $\alpha\gamma$ \\
$\beta$ & $\alpha\beta$ & $\beta^2$ & $\beta\gamma$ \\
$\gamma$ & $\alpha\gamma$ & $\beta\gamma$ & $\gamma^2$ \\
\hline
\end{tabular}
\end{table}
\section*{Names}
\begin{table}[ht]
\centering
\begin{tabular}{rrrrl}
\hline
Sepal.Length & Sepal.Width & Petal.Length & Petal.Width & Species \\
\hline
5.10 & 3.50 & 1.40 & 0.20 & setosa \\
4.90 & 3.00 & 1.40 & 0.20 & setosa \\
4.70 & 3.20 & 1.30 & 0.20 & setosa \\
4.60 & 3.10 & 1.50 & 0.20 & setosa \\
5.00 & 3.60 & 1.40 & 0.20 & setosa \\
5.40 & 3.90 & 1.70 & 0.40 & setosa \\
\hline
\end{tabular}
\end{table}
\end{document}
This chunk below is from the child document.
<<test-child, out.width='2in'>>=
1+1
rnorm(5)
plot(1)
boxplot(1:10)
str(mtcars)
@
\documentclass{article}
\begin{document}
<<test-main>>=
options(width = 60)
summary(iris)
@
Let's see how to work with child documents in knitr. Below we input
the file \textsf{087-child-example-child.rnw}:
<<child-demo, child='087-child-example-child.rnw'>>=
@
Done!
\end{document}
\documentclass{article}\usepackage[]{graphicx}\usepackage[]{color}
%% maxwidth is the original width if it is less than linewidth
%% otherwise use linewidth (to make sure the graphics do not exceed the margin)
\makeatletter
\def\maxwidth{ %
\ifdim\Gin@nat@width>\linewidth
\linewidth
\else
\Gin@nat@width
\fi
}
\makeatother
\definecolor{fgcolor}{rgb}{0.2, 0.2, 0.2}
\newcommand{\hlnumber}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlfunctioncall}[1]{\textcolor[rgb]{0.501960784313725,0,0.329411764705882}{\textbf{#1}}}%
\newcommand{\hlstring}[1]{\textcolor[rgb]{0.6,0.6,1}{#1}}%
\newcommand{\hlkeyword}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlargument}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlcomment}[1]{\textcolor[rgb]{0.180392156862745,0.6,0.341176470588235}{#1}}%
\newcommand{\hlroxygencomment}[1]{\textcolor[rgb]{0.43921568627451,0.47843137254902,0.701960784313725}{#1}}%
\newcommand{\hlformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hleqformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlassignement}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlpackage}[1]{\textcolor[rgb]{0.588235294117647,0.709803921568627,0.145098039215686}{#1}}%
\newcommand{\hlslot}[1]{\textit{#1}}%
\newcommand{\hlsymbol}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlprompt}[1]{\textcolor[rgb]{0.2,0.2,0.2}{#1}}%
\usepackage{framed}
\makeatletter
\newenvironment{kframe}{%
\def\at@end@of@kframe{}%
\ifinner\ifhmode%
\def\at@end@of@kframe{\end{minipage}}%
\begin{minipage}{\columnwidth}%
\fi\fi%
\def\FrameCommand##1{\hskip\@totalleftmargin \hskip-\fboxsep
\colorbox{shadecolor}{##1}\hskip-\fboxsep
% There is no \\@totalrightmargin, so:
\hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth}%
\MakeFramed {\advance\hsize-\width
\@totalleftmargin\z@ \linewidth\hsize
\@setminipage}}%
{\par\unskip\endMakeFramed%
\at@end@of@kframe}
\makeatother
\definecolor{shadecolor}{rgb}{.97, .97, .97}
\definecolor{messagecolor}{rgb}{0, 0, 0}
\definecolor{warningcolor}{rgb}{1, 0, 1}
\definecolor{errorcolor}{rgb}{1, 0, 0}
\newenvironment{knitrout}{}{} % an empty environment to be redefined in TeX
\usepackage{alltt}
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
\begin{document}
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlfunctioncall{options}(width = 60)
\hlfunctioncall{summary}(iris)
\end{alltt}
\begin{verbatim}
## Sepal.Length Sepal.Width Petal.Length Petal.Width
## Min. :4.30 Min. :2.00 Min. :1.00 Min. :0.1
## 1st Qu.:5.10 1st Qu.:2.80 1st Qu.:1.60 1st Qu.:0.3
## Median :5.80 Median :3.00 Median :4.35 Median :1.3
## Mean :5.84 Mean :3.06 Mean :3.76 Mean :1.2
## 3rd Qu.:6.40 3rd Qu.:3.30 3rd Qu.:5.10 3rd Qu.:1.8
## Max. :7.90 Max. :4.40 Max. :6.90 Max. :2.5
## Species
## setosa :50
## versicolor:50
## virginica :50
##
##
##
\end{verbatim}
\end{kframe}
\end{knitrout}
Let's see how to work with child documents in knitr. Below we input
the file \textsf{087-child-example-child.rnw}:
This chunk below is from the child document.
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
1 + 1
\end{alltt}
\begin{verbatim}
## [1] 2
\end{verbatim}
\begin{alltt}
\hlfunctioncall{rnorm}(5)
\end{alltt}
\begin{verbatim}
## [1] -0.56048 -0.23018 1.55871 0.07051 0.12929
\end{verbatim}
\begin{alltt}
\hlfunctioncall{plot}(1)
\end{alltt}
\end{kframe}
\includegraphics[width=2in]{figure/087-child-example-test-child1}
\begin{kframe}\begin{alltt}
\hlfunctioncall{boxplot}(1:10)
\end{alltt}
\end{kframe}
\includegraphics[width=2in]{figure/087-child-example-test-child2}
\begin{kframe}\begin{alltt}
\hlfunctioncall{str}(mtcars)
\end{alltt}
\begin{verbatim}
## 'data.frame': 32 obs. of 11 variables:
## $ mpg : num 21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
## $ cyl : num 6 6 4 6 8 6 8 4 4 6 ...
## $ disp: num 160 160 108 258 360 ...
## $ hp : num 110 110 93 110 175 105 245 62 95 123 ...
## $ drat: num 3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 ...
## $ wt : num 2.62 2.88 2.32 3.21 3.44 ...
## $ qsec: num 16.5 17 18.6 19.4 17 ...
## $ vs : num 0 0 1 1 0 1 0 1 1 1 ...
## $ am : num 1 1 1 0 0 0 0 0 0 0 ...
## $ gear: num 4 4 4 3 3 3 3 4 4 4 ...
## $ carb: num 4 4 1 1 2 1 4 2 2 4 ...
\end{verbatim}
\end{kframe}
\end{knitrout}
Done!
\end{document}

% Converting Markdown to Other Formats with knitr::pandoc() % Yihui Xie % March 1st, 2013

A bit introduction here.

Start with a cool section

You can use traditional Markdown syntax, such as links and code.

Followed by another section

Of course you can write lists:

  • apple
  • pear
  • banana

Or ordered lists:

  1. items
  2. will
  3. be
  4. ordered
    • nested
    • items

More sections

Hi

hi hi

Hello

hello hello

Howdy

howdy howdy

Okay, some R code

fit = lm(dist ~ speed, data = cars)
b = coef(fit)  # coefficients
summary(fit)
## 
## Call:
## lm(formula = dist ~ speed, data = cars)
## 
## Residuals:
##    Min     1Q Median     3Q    Max 
## -29.07  -9.53  -2.27   9.21  43.20 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept)  -17.579      6.758   -2.60    0.012 *  
## speed          3.932      0.416    9.46  1.5e-12 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 15.4 on 48 degrees of freedom
## Multiple R-squared:  0.651,	Adjusted R-squared:  0.644 
## F-statistic: 89.6 on 1 and 48 DF,  p-value: 1.49e-12

The code will be highlighted in all output formats.

And some pictures

par(mfrow = c(2, 2), pch = 20, mar = c(4, 4, 2, 0.1), bg = "white")
plot(fit)

Regression diagnostics

A little bit math

Our regression equation is $Y=-17.5791+3.9324x$, and the model is:

$$ Y = \beta_0 + \beta_1 x + \epsilon$$

library(knitr)
# this feature comes in v1.2
stopifnot(packageVersion('knitr') > '1.1')
# configurations are embedded in the input file
knit('088-pandoc-embedded.Rmd')
# default is HTML output
pandoc('088-pandoc-embedded.md')
# it is also possible to convert md to pdf through xelatex
pandoc('088-pandoc-embedded.md', format = 'latex')
% Converting Markdown to Other Formats with knitr::pandoc()
% [Yihui Xie](http://yihui.name)
% March 1st, 2013
<!--pandoc
format: html
s:
mathjax:
number-sections:
format: latex
number-sections:
-->
A bit _introduction_ here.
# Start with a cool section
You can use traditional **Markdown** syntax, such as [links](http://yihui.name/knitr) and `code`.
# Followed by another section
Of course you can write lists:
- apple
- pear
- banana
Or ordered lists:
1. items
1. will
1. be
1. ordered
- nested
- items
# More sections
## Hi
hi hi
## Hello
hello hello
## Howdy
howdy howdy
# Okay, some R code
```{r linear-model}
fit = lm(dist ~ speed, data = cars)
b = coef(fit) # coefficients
summary(fit)
```
The code will be highlighted in all output formats.
# And some pictures
```{r lm-vis, fig.cap='Regression diagnostics'}
par(mfrow = c(2, 2), pch = 20, mar = c(4, 4, 2, .1), bg = 'white')
plot(fit)
```
# A little bit math
Our regression equation is $Y=`r b[1]`+`r b[2]`x$, and the model is:
$$ Y = \beta_0 + \beta_1 x + \epsilon$$
= The Book Title
:author: A Knitter
== The first chapter
Nec vitae mus fringilla eu vel pede sed pellentesque. Nascetur fugiat
nobis. Eu felis id mauris sollicitudin ut. Sem volutpat feugiat.
Ornare convallis urna vitae.
Nec mauris sed aliquam nam mauris dolor lorem imperdiet.
== The second chapter
Ut suspendisse nulla. Auctor felis facilisis. Rutrum vivamus nec
lectus porttitor dui dapibus eu ridiculus tempor sodales et. Sit a
cras. Id tellus cubilia erat.
Quisque nullam et. Blandit dui tempor. Posuere in elit diam egestas
sem vivamus vel ac.
== Some R examples
Some text-based examples.
// begin.rcode test
1+1
rnorm(5)
1:2+1:3 # a warning
f=function(){message('Aloha, this is a friendly message!')}
f()
1+'a' # mision impossible
// end.rcode
And you know the value of pi is +r pi+. Let's try some graphics too.
// begin.rcode cool-plot, fig.width=5, fig.height=4, fig.cap='A wonderful plot.'
par(mar=c(4, 4, .1, .1))
plot(cars, pch=19)
// end.rcode
Ready to get started?
= The Book Title
:author: A Knitter
== The first chapter
Nec vitae mus fringilla eu vel pede sed pellentesque. Nascetur fugiat
nobis. Eu felis id mauris sollicitudin ut. Sem volutpat feugiat.
Ornare convallis urna vitae.
Nec mauris sed aliquam nam mauris dolor lorem imperdiet.
== The second chapter
Ut suspendisse nulla. Auctor felis facilisis. Rutrum vivamus nec
lectus porttitor dui dapibus eu ridiculus tempor sodales et. Sit a
cras. Id tellus cubilia erat.
Quisque nullam et. Blandit dui tempor. Posuere in elit diam egestas
sem vivamus vel ac.
== Some R examples
Some text-based examples.
[source,r]
----
1 + 1
----
----
## [1] 2
----
[source,r]
----
rnorm(5)
----
----
## [1] -0.56048 -0.23018 1.55871 0.07051 0.12929
----
[source,r]
----
1:2 + 1:3 # a warning
----
[WARNING]
====
.Warning
longer object length is not a multiple of shorter object length
====
----
## [1] 2 4 4
----
[source,r]
----
f = function() {
message("Aloha, this is a friendly message!")
}
f()
----
[NOTE]
====
.Message
Aloha, this is a friendly message!
====
[source,r]
----
1 + "a" # mision impossible
----
[CAUTION]
====
.Error
non-numeric argument to binary operator
====
And you know the value of pi is 3.1416. Let's try some graphics too.
[source,r]
----
par(mar = c(4, 4, 0.1, 0.1))
plot(cars, pch = 19)
----
.A wonderful plot.
image::figure/089-minimal-cool-plot.png[A wonderful plot.,align=default]
Ready to get started?

Compile C code

# is gcc there?
Sys.which("gcc")
##            gcc 
## "/usr/bin/gcc"

Does engine = 'c' work?

void square(double *x) {
  *x = *x * *x;
}

Test the square() function:

.C("square", 9)
## [[1]]
## [1] 81
.C("square", 123)
## [[1]]
## [1] 15129
# Compile C code
```{r}
# is gcc there?
Sys.which('gcc')
```
Does `engine = 'c'` work?
```{r test-c, engine='c', results='hide'}
void square(double *x) {
*x = *x * *x;
}
```
Test the `square()` function:
```{r}
.C('square', 9)
.C('square', 123)
```
\documentclass{article}
\usepackage{booktabs}
\usepackage{longtable}
\title{Demos of tables with \texttt{kable()} in knitr}
\author{Yihui Xie}
\begin{document}
\maketitle
<<setup, include=FALSE>>=
# in this document we mainly use results='asis', so set it globally
opts_chunk$set(results='asis')
@
The function \texttt{kable()} is a simple table generator. Unlike
sophisticated packages (e.g. \textbf{xtable}, which has more than 30
arguments), this function only has a minimal number of arguments to generate
simple tables.
<<test-a>>=
library(knitr)
kable(head(iris))
@
\section{No row names}
<<test-b>>=
kable(head(iris), row.names=FALSE)
@
\section{At most 3 digits}
<<test-c>>=
kable(matrix(rnorm(20),4), digits=3)
@
\section{Alignment}
By default, numeric columns are right-aligned, and other columns are
left-aligned.
<<test-d>>=
kable(head(iris), align=c('l', 'c', 'r', 'l', 'r'))
@
\section{Default tables are ugly}
Let's use the \textbf{booktabs} package. The air is suddenly fresh!
<<test-e>>=
kable(head(iris), row.names=FALSE, booktabs=TRUE)
kable(head(mtcars[, 1:7]), booktabs=TRUE)
@
\section{Long tables}
<<test-f>>=
kable(mtcars[, 1:7], longtable=TRUE, booktabs=TRUE)
@
\section{Want more features?}
No, that is all I have. You should turn to other packages for help. I'm not
going to reinvent their wheels.
\end{document}
\documentclass{article}\usepackage[]{graphicx}\usepackage[]{color}
%% maxwidth is the original width if it is less than linewidth
%% otherwise use linewidth (to make sure the graphics do not exceed the margin)
\makeatletter
\def\maxwidth{ %
\ifdim\Gin@nat@width>\linewidth
\linewidth
\else
\Gin@nat@width
\fi
}
\makeatother
\definecolor{fgcolor}{rgb}{0.2, 0.2, 0.2}
\newcommand{\hlnumber}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlfunctioncall}[1]{\textcolor[rgb]{0.501960784313725,0,0.329411764705882}{\textbf{#1}}}%
\newcommand{\hlstring}[1]{\textcolor[rgb]{0.6,0.6,1}{#1}}%
\newcommand{\hlkeyword}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlargument}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlcomment}[1]{\textcolor[rgb]{0.180392156862745,0.6,0.341176470588235}{#1}}%
\newcommand{\hlroxygencomment}[1]{\textcolor[rgb]{0.43921568627451,0.47843137254902,0.701960784313725}{#1}}%
\newcommand{\hlformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hleqformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlassignement}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlpackage}[1]{\textcolor[rgb]{0.588235294117647,0.709803921568627,0.145098039215686}{#1}}%
\newcommand{\hlslot}[1]{\textit{#1}}%
\newcommand{\hlsymbol}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlprompt}[1]{\textcolor[rgb]{0.2,0.2,0.2}{#1}}%
\usepackage{framed}
\makeatletter
\newenvironment{kframe}{%
\def\at@end@of@kframe{}%
\ifinner\ifhmode%
\def\at@end@of@kframe{\end{minipage}}%
\begin{minipage}{\columnwidth}%
\fi\fi%
\def\FrameCommand##1{\hskip\@totalleftmargin \hskip-\fboxsep
\colorbox{shadecolor}{##1}\hskip-\fboxsep
% There is no \\@totalrightmargin, so:
\hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth}%
\MakeFramed {\advance\hsize-\width
\@totalleftmargin\z@ \linewidth\hsize
\@setminipage}}%
{\par\unskip\endMakeFramed%
\at@end@of@kframe}
\makeatother
\definecolor{shadecolor}{rgb}{.97, .97, .97}
\definecolor{messagecolor}{rgb}{0, 0, 0}
\definecolor{warningcolor}{rgb}{1, 0, 1}
\definecolor{errorcolor}{rgb}{1, 0, 0}
\newenvironment{knitrout}{}{} % an empty environment to be redefined in TeX
\usepackage{alltt}
\usepackage{booktabs}
\usepackage{longtable}
\title{Demos of tables with \texttt{kable()} in knitr}
\author{Yihui Xie}
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
\begin{document}
\maketitle
The function \texttt{kable()} is a simple table generator. Unlike
sophisticated packages (e.g. \textbf{xtable}, which has more than 30
arguments), this function only has a minimal number of arguments to generate
simple tables.
\begin{kframe}
\begin{alltt}
\hlfunctioncall{library}(knitr)
\hlfunctioncall{kable}(\hlfunctioncall{head}(iris))
\end{alltt}
\end{kframe}\begin{tabular}{l|r|r|r|r|l}
\hline
& Sepal.Length & Sepal.Width & Petal.Length & Petal.Width & Species\\
\hline
1 & 5.1 & 3.5 & 1.4 & 0.2 & setosa\\
\hline
2 & 4.9 & 3.0 & 1.4 & 0.2 & setosa\\
\hline
3 & 4.7 & 3.2 & 1.3 & 0.2 & setosa\\
\hline
4 & 4.6 & 3.1 & 1.5 & 0.2 & setosa\\
\hline
5 & 5.0 & 3.6 & 1.4 & 0.2 & setosa\\
\hline
6 & 5.4 & 3.9 & 1.7 & 0.4 & setosa\\
\hline
\end{tabular}
\section{No row names}
\begin{kframe}
\begin{alltt}
\hlfunctioncall{kable}(\hlfunctioncall{head}(iris), row.names = FALSE)
\end{alltt}
\end{kframe}\begin{tabular}{r|r|r|r|l}
\hline
Sepal.Length & Sepal.Width & Petal.Length & Petal.Width & Species\\
\hline
5.1 & 3.5 & 1.4 & 0.2 & setosa\\
\hline
4.9 & 3.0 & 1.4 & 0.2 & setosa\\
\hline
4.7 & 3.2 & 1.3 & 0.2 & setosa\\
\hline
4.6 & 3.1 & 1.5 & 0.2 & setosa\\
\hline
5.0 & 3.6 & 1.4 & 0.2 & setosa\\
\hline
5.4 & 3.9 & 1.7 & 0.4 & setosa\\
\hline
\end{tabular}
\section{At most 3 digits}
\begin{kframe}
\begin{alltt}
\hlfunctioncall{kable}(\hlfunctioncall{matrix}(\hlfunctioncall{rnorm}(20), 4), digits = 3)
\end{alltt}
\end{kframe}\begin{tabular}{r|r|r|r|r}
\hline
-0.560 & 0.129 & -0.687 & 0.401 & 0.498\\
\hline
-0.230 & 1.715 & -0.446 & 0.111 & -1.967\\
\hline
1.559 & 0.461 & 1.224 & -0.556 & 0.701\\
\hline
0.071 & -1.265 & 0.360 & 1.787 & -0.473\\
\hline
\end{tabular}
\section{Alignment}
By default, numeric columns are right-aligned, and other columns are
left-aligned.
\begin{kframe}
\begin{alltt}
\hlfunctioncall{kable}(\hlfunctioncall{head}(iris), align = \hlfunctioncall{c}(\hlstring{"l"}, \hlstring{"c"}, \hlstring{"r"}, \hlstring{"l"}, \hlstring{"r"}))
\end{alltt}
\end{kframe}\begin{tabular}{l|l|c|r|l|r}
\hline
& Sepal.Length & Sepal.Width & Petal.Length & Petal.Width & Species\\
\hline
1 & 5.1 & 3.5 & 1.4 & 0.2 & setosa\\
\hline
2 & 4.9 & 3.0 & 1.4 & 0.2 & setosa\\
\hline
3 & 4.7 & 3.2 & 1.3 & 0.2 & setosa\\
\hline
4 & 4.6 & 3.1 & 1.5 & 0.2 & setosa\\
\hline
5 & 5.0 & 3.6 & 1.4 & 0.2 & setosa\\
\hline
6 & 5.4 & 3.9 & 1.7 & 0.4 & setosa\\
\hline
\end{tabular}
\section{Default tables are ugly}
Let's use the \textbf{booktabs} package. The air is suddenly fresh!
\begin{kframe}
\begin{alltt}
\hlfunctioncall{kable}(\hlfunctioncall{head}(iris), row.names = FALSE, booktabs = TRUE)
\end{alltt}
\end{kframe}\begin{tabular}{rrrrl}
\toprule
Sepal.Length & Sepal.Width & Petal.Length & Petal.Width & Species\\
\midrule
5.1 & 3.5 & 1.4 & 0.2 & setosa\\
\midrule
4.9 & 3.0 & 1.4 & 0.2 & setosa\\
\midrule
4.7 & 3.2 & 1.3 & 0.2 & setosa\\
\midrule
4.6 & 3.1 & 1.5 & 0.2 & setosa\\
\midrule
5.0 & 3.6 & 1.4 & 0.2 & setosa\\
\midrule
5.4 & 3.9 & 1.7 & 0.4 & setosa\\
\bottomrule
\end{tabular}
\begin{kframe}\begin{alltt}
\hlfunctioncall{kable}(\hlfunctioncall{head}(mtcars[, 1:7]), booktabs = TRUE)
\end{alltt}
\end{kframe}\begin{tabular}{lrrrrrrr}
\toprule
& mpg & cyl & disp & hp & drat & wt & qsec\\
\midrule
Mazda RX4 & 21.0 & 6 & 160 & 110 & 3.90 & 2.620 & 16.46\\
\midrule
Mazda RX4 Wag & 21.0 & 6 & 160 & 110 & 3.90 & 2.875 & 17.02\\
\midrule
Datsun 710 & 22.8 & 4 & 108 & 93 & 3.85 & 2.320 & 18.61\\
\midrule
Hornet 4 Drive & 21.4 & 6 & 258 & 110 & 3.08 & 3.215 & 19.44\\
\midrule
Hornet Sportabout & 18.7 & 8 & 360 & 175 & 3.15 & 3.440 & 17.02\\
\midrule
Valiant & 18.1 & 6 & 225 & 105 & 2.76 & 3.460 & 20.22\\
\bottomrule
\end{tabular}
\section{Long tables}
\begin{kframe}
\begin{alltt}
\hlfunctioncall{kable}(mtcars[, 1:7], longtable = TRUE, booktabs = TRUE)
\end{alltt}
\end{kframe}\begin{longtable}{lrrrrrrr}
\toprule
& mpg & cyl & disp & hp & drat & wt & qsec\\
\midrule
Mazda RX4 & 21.0 & 6 & 160.0 & 110 & 3.90 & 2.620 & 16.46\\
\midrule
Mazda RX4 Wag & 21.0 & 6 & 160.0 & 110 & 3.90 & 2.875 & 17.02\\
\midrule
Datsun 710 & 22.8 & 4 & 108.0 & 93 & 3.85 & 2.320 & 18.61\\
\midrule
Hornet 4 Drive & 21.4 & 6 & 258.0 & 110 & 3.08 & 3.215 & 19.44\\
\midrule
Hornet Sportabout & 18.7 & 8 & 360.0 & 175 & 3.15 & 3.440 & 17.02\\
\midrule
Valiant & 18.1 & 6 & 225.0 & 105 & 2.76 & 3.460 & 20.22\\
\midrule
Duster 360 & 14.3 & 8 & 360.0 & 245 & 3.21 & 3.570 & 15.84\\
\midrule
Merc 240D & 24.4 & 4 & 146.7 & 62 & 3.69 & 3.190 & 20.00\\
\midrule
Merc 230 & 22.8 & 4 & 140.8 & 95 & 3.92 & 3.150 & 22.90\\
\midrule
Merc 280 & 19.2 & 6 & 167.6 & 123 & 3.92 & 3.440 & 18.30\\
\midrule
Merc 280C & 17.8 & 6 & 167.6 & 123 & 3.92 & 3.440 & 18.90\\
\midrule
Merc 450SE & 16.4 & 8 & 275.8 & 180 & 3.07 & 4.070 & 17.40\\
\midrule
Merc 450SL & 17.3 & 8 & 275.8 & 180 & 3.07 & 3.730 & 17.60\\
\midrule
Merc 450SLC & 15.2 & 8 & 275.8 & 180 & 3.07 & 3.780 & 18.00\\
\midrule
Cadillac Fleetwood & 10.4 & 8 & 472.0 & 205 & 2.93 & 5.250 & 17.98\\
\midrule
Lincoln Continental & 10.4 & 8 & 460.0 & 215 & 3.00 & 5.424 & 17.82\\
\midrule
Chrysler Imperial & 14.7 & 8 & 440.0 & 230 & 3.23 & 5.345 & 17.42\\
\midrule
Fiat 128 & 32.4 & 4 & 78.7 & 66 & 4.08 & 2.200 & 19.47\\
\midrule
Honda Civic & 30.4 & 4 & 75.7 & 52 & 4.93 & 1.615 & 18.52\\
\midrule
Toyota Corolla & 33.9 & 4 & 71.1 & 65 & 4.22 & 1.835 & 19.90\\
\midrule
Toyota Corona & 21.5 & 4 & 120.1 & 97 & 3.70 & 2.465 & 20.01\\
\midrule
Dodge Challenger & 15.5 & 8 & 318.0 & 150 & 2.76 & 3.520 & 16.87\\
\midrule
AMC Javelin & 15.2 & 8 & 304.0 & 150 & 3.15 & 3.435 & 17.30\\
\midrule
Camaro Z28 & 13.3 & 8 & 350.0 & 245 & 3.73 & 3.840 & 15.41\\
\midrule
Pontiac Firebird & 19.2 & 8 & 400.0 & 175 & 3.08 & 3.845 & 17.05\\
\midrule
Fiat X1-9 & 27.3 & 4 & 79.0 & 66 & 4.08 & 1.935 & 18.90\\
\midrule
Porsche 914-2 & 26.0 & 4 & 120.3 & 91 & 4.43 & 2.140 & 16.70\\
\midrule
Lotus Europa & 30.4 & 4 & 95.1 & 113 & 3.77 & 1.513 & 16.90\\
\midrule
Ford Pantera L & 15.8 & 8 & 351.0 & 264 & 4.22 & 3.170 & 14.50\\
\midrule
Ferrari Dino & 19.7 & 6 & 145.0 & 175 & 3.62 & 2.770 & 15.50\\
\midrule
Maserati Bora & 15.0 & 8 & 301.0 & 335 & 3.54 & 3.570 & 14.60\\
\midrule
Volvo 142E & 21.4 & 4 & 121.0 & 109 & 4.11 & 2.780 & 18.60\\
\bottomrule
\end{longtable}
\section{Want more features?}
No, that is all I have. You should turn to other packages for help. I'm not
going to reinvent their wheels.
\end{document}
\documentclass{article}
\usepackage{url}
\begin{document}
A bug reported at \url{http://cos.name/cn/topic/110742}.
<<rgl-demo>>=
knit_hooks$set(rgl = hook_rgl)
head(hook_rgl) # the hook function is defined as this
@
Then we only have to set the chunk option \texttt{rgl=TRUE}:
<<fancy-rgl, rgl=TRUE, dev='png', out.width='3in', fig.align='center', fig.show='hold'>>=
library(rgl)
demo('bivar', package='rgl', echo=FALSE)
par3d(zoom=.7)
@
\end{document}
\documentclass{article}\usepackage[]{graphicx}\usepackage[]{color}
%% maxwidth is the original width if it is less than linewidth
%% otherwise use linewidth (to make sure the graphics do not exceed the margin)
\makeatletter
\def\maxwidth{ %
\ifdim\Gin@nat@width>\linewidth
\linewidth
\else
\Gin@nat@width
\fi
}
\makeatother
\definecolor{fgcolor}{rgb}{0.2, 0.2, 0.2}
\newcommand{\hlnumber}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlfunctioncall}[1]{\textcolor[rgb]{0.501960784313725,0,0.329411764705882}{\textbf{#1}}}%
\newcommand{\hlstring}[1]{\textcolor[rgb]{0.6,0.6,1}{#1}}%
\newcommand{\hlkeyword}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlargument}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlcomment}[1]{\textcolor[rgb]{0.180392156862745,0.6,0.341176470588235}{#1}}%
\newcommand{\hlroxygencomment}[1]{\textcolor[rgb]{0.43921568627451,0.47843137254902,0.701960784313725}{#1}}%
\newcommand{\hlformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hleqformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{#1}}%
\newcommand{\hlassignement}[1]{\textcolor[rgb]{0,0,0}{\textbf{#1}}}%
\newcommand{\hlpackage}[1]{\textcolor[rgb]{0.588235294117647,0.709803921568627,0.145098039215686}{#1}}%
\newcommand{\hlslot}[1]{\textit{#1}}%
\newcommand{\hlsymbol}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlprompt}[1]{\textcolor[rgb]{0.2,0.2,0.2}{#1}}%
\usepackage{framed}
\makeatletter
\newenvironment{kframe}{%
\def\at@end@of@kframe{}%
\ifinner\ifhmode%
\def\at@end@of@kframe{\end{minipage}}%
\begin{minipage}{\columnwidth}%
\fi\fi%
\def\FrameCommand##1{\hskip\@totalleftmargin \hskip-\fboxsep
\colorbox{shadecolor}{##1}\hskip-\fboxsep
% There is no \\@totalrightmargin, so:
\hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth}%
\MakeFramed {\advance\hsize-\width
\@totalleftmargin\z@ \linewidth\hsize
\@setminipage}}%
{\par\unskip\endMakeFramed%
\at@end@of@kframe}
\makeatother
\definecolor{shadecolor}{rgb}{.97, .97, .97}
\definecolor{messagecolor}{rgb}{0, 0, 0}
\definecolor{warningcolor}{rgb}{1, 0, 1}
\definecolor{errorcolor}{rgb}{1, 0, 0}
\newenvironment{knitrout}{}{} % an empty environment to be redefined in TeX
\usepackage{alltt}
\usepackage{url}
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
\begin{document}
A bug reported at \url{http://cos.name/cn/topic/110742}.
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
knit_hooks$\hlfunctioncall{set}(rgl = hook_rgl)
\hlfunctioncall{head}(hook_rgl) \hlcomment{# the hook function is defined as this}
\end{alltt}
\begin{verbatim}
##
## 1 function (before, options, envir)
## 2 {
## 3 library(rgl)
## 4 if (before || rgl.cur() == 0)
## 5 return()
## 6 name = fig_path("", options)
\end{verbatim}
\end{kframe}
\end{knitrout}
Then we only have to set the chunk option \texttt{rgl=TRUE}:
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlfunctioncall{library}(rgl)
\hlfunctioncall{demo}(\hlstring{"bivar"}, package = \hlstring{"rgl"}, echo = FALSE)
\end{alltt}
{\ttfamily\noindent\itshape\color{messagecolor}{\#\# Loading required package: MASS}}\begin{alltt}
\hlfunctioncall{par3d}(zoom = 0.7)
\end{alltt}
{\centering \includegraphics[width=3in]{figure/092-latex-rgl-fancy-rgl}
}
\end{kframe}
\end{knitrout}
\end{document}
This is a copy of the knitr example dir.

knitr examples

This repository is a collection of knitr examples. It is both for my own test purpose and for other knitters to learn about this package.

For each input file, there is an output file, e.g. 001-minimal.Rmd corresponds to 001-minimal.md.

#!/bin/bash
prefix=${1%.*}-
Rscript -e "library(knitr)"\
-e "opts_knit\$set(base.url='http://animation.r-forge.r-project.org/knitr-ex/', progress=FALSE)"\
-e "opts_chunk\$set(cache.path='cache/$prefix', fig.path='figure/$prefix')"\
-e "set.seed(123); knit('$1')"
# if there is an extra argument, compile tex to pdf
if [ "$2" != '' ]; then
texi2pdf -c ${1%.*}.tex
fi
#!/bin/bash
ls | grep -E '^[0-9].*\.(brew|R(nw|md|tex|html|rst|asciidoc))$' | xargs -n1 -P4 ./k
knit:
./knitall; \
./k "078-chinese-big5.rnw', '078-chinese-big5.ctx', encoding='BIG5"; \
./k "076-chinese-gb2312.rnw', encoding='GB2312"
pdf:
ls *.tex | xargs -n1 -P4 texi2pdf -c -q
pandoc:
Rscript 084-pandoc.R && Rscript 088-pandoc-embedded.R
deps:
Rscript -e "for (i in c('ggplot2', 'mapproj', 'Hmisc', 'xtable', 'gridExtra', 'Rcpp', 'RcppArmadillo', 'diagram'))" \
-e "if (!require(i, character.only=TRUE)) install.packages(i)"
clean:
$(RM) *.log *.aux *.toc *.docx *.epub *.odt 084-pandoc-slides.html; \
ls *.Rmd | sed 's/\.Rmd$$/.html/' | xargs $(RM); \
find figure/ | grep -E 'figure/[a-zA-Z]' | xargs $(RM)
strip:
for i in `ls | grep -E '^[0-9].*\.(brew|R(nw|md|tex|html|rst))$$'`; do sed -i "s/[[:space:]]*$$//" $$i; done
mount:
sshfs yihui@r-forge.r-project.org:/srv/gforge/chroot/home/groups/animation/htdocs/knitr-ex ./r-forge
unmount:
fusermount -u ./r-forge
sync:
cp -u ./figure/*.png ./r-forge/figure/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment