在 rmarkdown for pdf (latex) 的 ggplot 中添加希腊字母

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

我正在 Rmarkdown 工作以准备一些讲座。我希望最终文档为 pdf 格式。我正在尝试使用 ggplot2 绘制不同 rho(希腊字母)值的散点图,以说明相关性及其外观。我希望每个面板都有 rho = r。使用 UTF-8 编码,我可以在隔离块中或通过编织 html 产生所需的结果。但是如果我用pdf编织,它就不行了

这是代码,我正在处理。

---
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))

```

这是我得到的错误。

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

这是我想要的 pdf 格式的 html 图。

感谢您的帮助!

您可以通过 label_bquote() 使用“plotmath”表达式,而不是使用 Unicode。除了最后一条语句外,保持原始代码中的所有内容相同:

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

请注意,您需要 == 才能在 plotmath 中获得一个等号。这会产生以下情节;它应该适用于所有输出设备: