8

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?

enter image description here

NelsonGon
  • 13,015
  • 7
  • 27
  • 57
Justas Mundeikis
  • 935
  • 1
  • 10
  • 19
  • https://stackoverflow.com/questions/42680619/greek-letter-in-title-of-r-markdown-document https://stackoverflow.com/questions/26821326/how-can-i-write-special-characters-in-rmarkdown-latex-documents – bbiasi May 25 '19 at 20:04
  • @bbiasi unfortunately, my problem does not concern the main document, but the embedded ggplot2 chart. I clear any problems in the main docckument with the header including `\usepackage[L7x]{fontenc}` – Justas Mundeikis May 27 '19 at 17:28
  • Are you using Windows? R on WIndows always has problems with UTF-8 encodings. – user2554330 Jun 01 '19 at 00:44
  • 1
    I opened a bounty on this question, I hope to help you. – bbiasi Jun 01 '19 at 02:44

1 Answers1

9

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:

success2

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.

asachet
  • 6,620
  • 2
  • 30
  • 74