I'm trying to knit to pdf a file with Lithuanian characters like ąčęėįšųž in RStudio from .Rmd file. While knitting to html works properly and the ggplot
title has the Lithuanian characters, when knitting to pdf ggplot
does create warnings and dismisses these characters.
Reproducible example:
---
title: "Untitled"
output:
pdf_document:
includes:
in_header: header_lt_text.txt
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(ggplot2)
```
## Lithuanian char: ĄČĘĖĮŠŲŪžąčęėįšųūž
```{r}
ggplot(iris, aes(Sepal.Length, Sepal.Width))+
geom_point(aes(col=Species))+
labs(title="Lithuanian char: ĄČĘĖĮŠŲŪžąčęėįšųūž")
```
I pass the header_lt_text.txt
with follwoing arguments:
\usepackage[utf8]{inputenc}
\usepackage[L7x]{fontenc}
\usepackage[lithuanian]{babel}
\usepackage{setspace}
\onehalfspacing
Any suggestions on how to make ggplot
create correct labels?
The problem is with the pdf
device and is only apparent when saving the picture as pdf (which you want because it looks much, much better). This is why it seems to "work" in some cases: the image is not rendered as pdf but e.g. as png. Thanks to @Konrad for correctly identifying the source of the problem.
To solve this, you need to pass the correct encoding to the pdf
device.
Fortunately, the pdf device (?pdf
) takes an encoding
argument and there is a chunk option to pass arguments to the device: dev.args
On Windows, an appropriate encoding is CP1257.enc
(Baltic):
```{r dev="pdf", dev.args=list(encoding="CP1257.enc")}
ggplot(iris, aes(Sepal.Length, Sepal.Width))+
geom_point(aes(col=Species))+
labs(title="Lithuanian char: ĄČĘĖĮŠŲŪžąčęėįšųūž")
```
You can see the other encodings available out of the box with: list.files(system.file("enc", package = "grDevices"))
Works well on my linux machine:
Alternatively, if you're happy to get png images inserted in the pdf, you can simply use dev="png"
in your chunk option. Doesn't look as good though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With