首页 > 解决方案 > 在 rmarkdown 的 ggplot 中为 pdf ( 乳胶 ) 添加希腊字母

问题描述

我正在Rmarkdown准备一些讲座。我希望最终文件为 pdf 格式。我正在尝试为 rho(希腊字母)的不同值绘制散点图,ggplot2以说明相关性及其可能的样子。我希望每个面板都有 rho = r。使用 UTF-8 编码,我可以在孤立的块中或通过 html 中的 knit 生成所需的结果。但是如果我用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 图。

在此处输入图像描述

谢谢您的帮助!

标签: rggplot2r-markdownbookdown

解决方案


除了使用 Unicode,您还可以通过label_bquote(). 保持原始代码中的所有内容都相同,除了最后一条语句:

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

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


推荐阅读