striatum
striatum

Reputation: 1598

Getting Unicode character in knitr R-figure snippet

Currently I am making my figs using "unprincipled" (opportunistic) way to get Unicode characters right. For example:

<<ClassFig>>=
pdf('figs/figA.pdf', h=6, w=6, encoding='CP1250')
plot(x, y, xlab='rečenica')
dev.off()
@

Now, I wonder how would I specify snippet (or global settings, as with opts_chunk$set()) properly to see Uncode characters that I need. For example:

<<ParadigmFig, fig.height=7, fig.width=15, out.width='1\\textwidth'>>=
plot(x, y, xlab='rečenica')
@

Currently, if I use the second, proper variant, I am getting dots instead of spec. character.

Upvotes: 4

Views: 907

Answers (1)

gagolews
gagolews

Reputation: 13056

Try generating this figure with cairo_pdf().

cairo_pdf('test.pdf', family="Helvetica")
plot(1:10, (1:10)^2, xlab=enc2utf8("ąśćźół"))
dev.off()

It may be important to change the font family to one of which knows about regional characters (I'm using Polish letters above). For OS X, this list may give you a hint on font family selection.

Now let's set up knitr to use these settings. Create an uncached code chunk at the beginning of the document with calls to:

library("knitr")
library("tikzDevice")
opts_chunk$set(
   dev='cairo_pdf',
   dev.args=list(family='DejaVu Sans')
   #out.width='5in', 
   #fig.width=5,
   #fig.height=5/sqrt(2),
   #fig.path='figures-knitr/',
   #fig.align='center',
)

(I've commented out the options which are meaningless here, but which you may also be interested in some day). You may find more details on chunk options here.

Here is an exemplary .Rnw file that (at least on my Linux) produces correct results:

\documentclass{article}

\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[T1,plmath]{polski}
\usepackage[polish]{babel}

\begin{document}

<<cache=FALSE,echo=FALSE,message=FALSE>>=
options(Encoding="UTF-8")
library("knitr")
library("tikzDevice")
opts_chunk$set(
   dev='cairo_pdf',
   dev.args=list(family='Helvetica')
   #out.width='5in', 
   #fig.width=5,
   #fig.height=5/sqrt(2),
   #fig.path='figures-knitr/',
   #fig.align='center',
)
@

<<>>=
plot(1:10, (1:10)^2, xlab="ąśćźół")
@

\end{document}

Upvotes: 2

Related Questions