Skip to content


Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: master
Fetching contributors…

Cannot retrieve contributors at this time

108 lines (87 sloc) 3.906 kb
%% LyX 2.1.2 created this file. For more info, see
%% Do not edit unless you really know what you are doing.
breaklinks=false,pdfborder={0 0 1},backref=false,colorlinks=false]
pdfstartview={XYZ null null 1}}
<<setup, include=FALSE, cache=FALSE>>=
opts_chunk$set(fig.path = 'figure/listings-')
options(formatR.arrow = TRUE)
\title{Using listings with knitr}
\author{Yihui Xie}
To use the \textbf{listings} package with \textbf{knitr}, all you
need to do is to call a function in your first setup chunk (that chunk
should be hidden from the output with \texttt{include=FALSE} and should
not be cached):
% I just want to echo the 2nd line
<<setup, echo=2>>=
This function modifies the output hooks and header information so
that the output is written in \textbf{listings} environments, which
are kindly provided by Frank Harrell and can be found in \url{}.
Of course you have to install the \textbf{listings} package if your
\LaTeX{} toolset does not include this package.
Now we can see how the results look like with our new settings:
set.seed(1121) # for reproducibility
sqrt(-1) # this will give you a warning message
Another chunk:
hook_rgl = function(before, options, envir) {
## after a chunk has been evaluated
if (before || !require('rgl') || rgl.cur() == 0) return() # no active device
name = paste(valid_prefix(options$fig.path), options$label, sep = '')
par3d(windowRect = 100 + options$dpi * c(0, 0, options$width, options$height))
Sys.sleep(.05) # need time to respond to window size change
fmt = opts_knit$get('out.format')
if (fmt %in% c('html', 'markdown', 'gfm', 'jekyll')) options$dev = 'png'
## support 3 formats: eps, pdf and png (default)
postscript = rgl.postscript(paste(name, '.eps', sep = ''), fmt = 'eps'),
pdf = rgl.postscript(paste(name, '.pdf', sep = ''), fmt = 'pdf'),
rgl.snapshot(paste(name, '.png', sep = ''), fmt = 'png'))
if (fmt == 'html') return(.plot.hook.html(c(name, 'png'), options))
if (fmt %in% c('markdown', 'gfm', 'jekyll'))
return(.plot.hook.markdown(c(name, 'png'), options))
paste(ifelse(options$align == 'center', '\\centering{}', ''), '\\includegraphics[',
sprintf('width=%s', options$out.width), ']{', name, '}\n', sep = '')
Well, we can do crazier things with \textbf{knitr}. Here we use the
\texttt{fig.cap} option to write plots into the \texttt{figure} environment
automatically, and the caption is generated from data dynamically
(see Figure \ref{fig:boxplot-ex}):
% set an option first
<<eval-opts, echo=FALSE>>=
opts_knit$set(eval.after = 'fig.cap') # evaluate fig.cap after the chunk
<<boxplot-ex, fig.height=2, out.width='.8\\linewidth', fig.cap=sprintf('This is a boxplot; the median is %.2f.', median(x))>>=
boxplot(x, horizontal=TRUE)
As we know, \texttt{figure} is a float environment, so it has floated
away from the R code to the top of this page. This should not be surprising
to \LaTeX{} users.
You should be able to compile the \TeX{} document and get a PDF file
like this one: \url{}.
For more information about out hooks, see \url{}.
Jump to Line
Something went wrong with that request. Please try again.