Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non English characters in ggplot within a knitr document

Tags:

r

ggplot2

knitr

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

like image 704
Justas Mundeikis Avatar asked May 25 '19 20:05

Justas Mundeikis


1 Answers

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.

like image 57
asachet Avatar answered Oct 30 '22 10:10

asachet