knitr documents with tikzDevice graphics

Setting up tikzDevice output in knitr may be a frustrating task, but gives outstandingly aesthetic, LaTeX-like figures.

Here are my global knitr settings for typesetting documents in Polish (in UTF-8, make sure your R also runs in a Unicode locale or change inputenc according to your preferences).

Run right after \begin{document} in an .Rnw source file:

<<MainSettings,echo=FALSE,cache=FALSE,warning=FALSE,message=FALSE>>=
options(width=71)
options(digits=7)

require("knitr")

opts_knit$set(progress = FALSE, verbose = FALSE) # works better with Kile

opts_chunk$set(
   keep.source=TRUE,
   out.width='5in',
   fig.width=5,
   fig.height=5/sqrt(2),
   fig.path='figures-knitr/filename-',  # a unique ID here if you got
   cache.path='cache-knitr/filename-',  # many documents in one dir
   cache=TRUE,
   tidy=FALSE,
   dev='tikz',
   external=TRUE,
   fig.align='center',
   size='small'
)

options(tikzDefaultEngine = "pdftex")

options(tikzLatexPackages = c(
   "\\usepackage{amsmath,amssymb,amsfonts}",
   "\\usepackage{tikz}",
   "\\usepackage[MeX,T1,plmath]{polski}",
   "\\usepackage[utf8]{inputenc}",
   "\\usepackage[T1]{fontenc}",
   "\\usetikzlibrary{calc}",
   "\\usepackage[polish]{babel}",
   "\\selectlanguage{polish}",
   "\\usepackage{standalone}"
))

options(tikzMetricsDictionary="~/R/tikzMetrics") # speeds tikz up

options(tikzDocumentDeclaration = "\\documentclass[10pt]{standalone}\n")

options(tikzMetricPackages = c(
   "\\usepackage[MeX,T1,plmath]{polski}",
   "\\usepackage[utf8]{inputenc}",
   "\\usepackage[T1]{fontenc}",
   "\\usetikzlibrary{calc}",
   "\\usepackage[polish]{babel}",
   "\\selectlanguage{polish}"
))


knit_theme$set(knit_theme$get("default"))
# print(knit_theme$get("default")) for more themes
@


Marek Gągolewski

Tagged with: , , , ,
Posted in Blog/LaTeX, Blog/R, Blog/R-bloggers, Blog/R-knitr