[Tex/LaTex] Special characters in knitr generated figure caption

input-encodingsknitrplotsweave

I would like to pass special characters and formatting with the knitr generated captions.

I am trying to understand two things:

1) Is it possible to pass LaTeX syntax through the caption?

2) How to define the encoding of the caption/subcaption strings?

Please consider the following MWE

\documentclass{article}
\usepackage{subfig}
\begin{document}

<<fig-sub, fig.cap='Three \textit{plots}', fig.subcap=c('Erdős–Rényi', 'Barabási-Albert'), out.width='.30\\linewidth',dev='tikz',sanitize=TRUE>>=
library(ggplot2)

x<-1:10
y<-rnorm(10)

ggplot(data.frame(x,y), aes(x,y)) + geom_line()
ggplot(data.frame(y,x), aes(y,x)) + geom_line()
@

\end{document}

Best Answer

The answer (I found) is pretty simple. knitr/R will pass to TeX special characters if correctly escaped (backslashed). It is also probably necessary to use double-quotes " " instead of single quotes ' '

\documentclass{article}
\usepackage{subfig}
\begin{document}

<<fig-sub, fig.cap="Three \\textit{plots}", fig.subcap=c("Erd\\H{o}s-R\\'enyi", "Barab\\'asi-Albert"), out.width='.30\\linewidth',dev='tikz',sanitize=TRUE>>=
library(ggplot2)

x<-1:10
y<-rnorm(10)

ggplot(data.frame(x,y), aes(x,y)) + geom_line()
ggplot(data.frame(y,x), aes(y,x)) + geom_line()
@

\end{document}