【问题标题】:Add greek letter in a ggplot in rmarkdown for pdf (latex)在 rmarkdown 的 ggplot 中为 pdf ( 乳胶 ) 添加希腊字母
【发布时间】:2021-10-31 23:57:45
【问题描述】:

我正在Rmarkdown 工作以准备一些讲座。我希望最终文件为 pdf 格式。我正在尝试使用ggplot2 绘制 rho(希腊字母)的不同值的散点图,以说明相关性及其可能的样子。我希望每个面板都有 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 图。

感谢您的帮助!

【问题讨论】:

    标签: r ggplot2 r-markdown bookdown


    【解决方案1】:

    您可以通过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 中获得一个等号。这会产生以下情节;它应该适用于所有输出设备:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多