POC
POC

Reputation: 278

Add greek letter in a ggplot in rmarkdown for pdf (latex)

I'm working in Rmarkdown to prepare some lectures. I would like the final document to be in pdf. I'm trying to plot scatterplots for different values of rho (greek letter) with ggplot2 to illustrate correlation and what it may looks like. I would like each panel to have rho = r. Using UTF-8 encoding, I can produce the desired results in the isolated chunk or by knit in html. But if I knit in pdf, it won't work

Here is the code, I'm working on.

---
title: "TEST"
output: pdf_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(ggplot2)
```

```{r, echo=FALSE}
set.seed(42)
n = 100
r = c(-.999, -.75, -.5, -.25, 0, .25, .5, .75, .999)
DATA = numeric()
P = numeric()
for(i in 1:length(r)){
  X = round(MASS::mvrnorm(n = n, 
                          mu = c(0,0), 
                          Sigma = matrix(c(1,r[i],r[i],1),2,2)),4)
  DATA = rbind(DATA,cbind(X,r[i]))
}

DATA = data.frame(DATA)
colnames(DATA) = c("Variable1", "Variable2", "Correlation")

P.labs = paste("\u03C1 = ",r)   # works in HTML, not in pdf
#P.labs = paste("$\\rho$ = ", r) # does not work
#P.labs = paste("\\rho = ", r)   # does not work
#P.labs = paste("rho = ", r)      # Resignation for pdf
names(P.labs) = r

ggplot(data = DATA, aes(x = Variable1,y = Variable2)) +
  geom_point() + 
  facet_wrap(vars(Correlation), ncol = 3, labeller = labeller(Correlation = P.labs))

```

Here is the error I get.

Error in stri_replace_all_charclass(str, "[\\u0020\\r\\n\\t]", " ", merge = TRUE) : 
invalid UTF-8 byte sequence detected; try calling stri_enc_toutf8()
Calls: <Anonymous> ... stri_trim -> stri_trim_both -> stri_replace_all_charclass

Here is the html figure that I would like in pdf.

enter image description here

Thank you for your help!

Upvotes: 2

Views: 455

Answers (1)

user2554330
user2554330

Reputation: 44788

Instead of using Unicode, you can use the "plotmath" expression via label_bquote(). Keep everything the same in your original code except the last statement:

ggplot(data = DATA, aes(x = Variable1,y = Variable2)) +
  geom_point() + 
  facet_wrap(vars(Correlation), ncol = 3, labeller = label_bquote(rho == .(Correlation)))

Note that you need == to get a single equal sign in plotmath. This produces the following plot; it should work in all output devices: screenshot

Upvotes: 2

Related Questions