2

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}
8

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}
  • 3
    I needed to quickly figure out how to type Erdos-Renyi with the correct accents in Latex, and this helped me: Erd\H{o}s-R\'enyi. Thanks. – hadi Jan 30 '14 at 18:51
0

Another option which might be better if you have a lot of captions with these special characters is to add the line \usepackage[utf8x]{inputenc} to preamble of the document and to add the line pdf.options(encoding = "CP1250") to the chunk.

So the changed MWE will look like this:

\documentclass{article}
\usepackage{subfig}
\usepackage[utf8x]{inputenc} 
\begin{document}


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

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}

Note: I obtained an error due to dev='tikz' so I skipped it. I hope your problem has nothing to do with this and it will work for anyway.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.