R Markdown 中 ggraph 节点中的希腊字母

Greek letters in ggraph nodes in R Markdown

当我在 RStudio 中 运行 下面的 R 脚本时,theta 显示正确。

---
title: "test"
output: pdf_document
---

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

# Greek letters
```{r ggraph}
nodes<-data.frame(label=c("θ","S"))
edges<-data.frame(from=c(2),to=c(1))
graph<-tbl_graph(nodes=nodes,edges=edges)
ggraph::ggraph(graph,layout="fr")+
    ggraph::geom_edge_link()+
    ggraph::geom_node_label(mapping = aes(label=label))     
```

但是当我编织它的时候,我收到这个错误信息(部分是丹麦语):

! Package inputenc Error: Unicode character θ (U+03B8) (inputenc) not set up for use with LaTeX.

Try other LaTeX engines instead (e.g., xelatex) if you are using pdflatex. For R Markdown users, see https://bookdown.org/yihui/rmarkdown/pdf-document.html Fejl: LaTeX failed to compile test.tex. See https://yihui.org/tinytex/r/#debugging for debugging tips. See test.log for more info. In addition: Advarselsbeskeder: 1: I grid.Call(C_textBounds, as.graphicsAnnot(x$label), x$x, x$y, : konverteringsfejl på 'θ' i 'mbcsToSbcs': punktum erstattet for 2: I grid.Call(C_textBounds, as.graphicsAnnot(x$label), x$x, x$y, : konverteringsfejl på 'θ' i 'mbcsToSbcs': punktum erstattet for 3: I grid.Call(C_textBounds, as.graphicsAnnot(x$label), x$x, x$y, : konverteringsfejl på 'θ' i 'mbcsToSbcs': punktum erstattet for 4: I grid.Call(C_textBounds, as.graphicsAnnot(x$label), x$x, x$y, : konverteringsfejl på 'θ' i 'mbcsToSbcs': punktum erstattet for 5: I grid.Call.graphics(C_text, as.graphicsAnnot(x$label), x$x, x$y, :
konverteringsfejl på 'θ' i 'mbcsToSbcs': punktum erstattet for 6: I grid.Call.graphics(C_text, as.graphicsAnnot(x$label), x$x, x$y, :
konverteringsfejl på 'θ' i 'mbcsToSbcs': punktum erstattet for 7: I grid.Call.graphics(C_text, as.graphicsAnnot(x$label), x$x, x$y, :
konverteringsfejl på 'θ' i 'mbcsToSbcs': punktum erstattet for 8: I grid.Call.graphics(C_text, as.graphicsAnnot(x$label), x$x, x$y, :
konverteringsfejl på 'θ' i 'mbcsToSbcs': punktum erstattet for Kørsel stoppet

我试过使用表达式(theta) 代替角色本身,但这不起作用。有什么想法吗?

可能有更好的方法来解决这个问题,但解决您的问题的一种方法是:

  1. 使用xelatexfontenc包;
  2. 强制 dev"jpeg""png" 或“cairo_pdf”以生成数字(θ 可能会导致其他设备出现问题)。

下面是我用过的 RMarkdown 文档

    ---
    title: "test"
    header_includes:
        - \usepackage[T1]{fontenc}
    output:
        pdf_document:
          latex_engine: xelatex
    ---


    ```{r setup, include=FALSE}
     knitr::opts_chunk$set(echo = TRUE, dev = "png", dpi = 300)
     library(tidygraph)
     library(ggraph)
     ```

    # Greek letters

    ```{r ggraph}
    library(ggraph)
    library(ggplot2)
    nodes<-data.frame(label=c("θ","S"))
    edges<-data.frame(from=c(2),to=c(1))
    graph<-tbl_graph(nodes=nodes,edges=edges)
    ggraph::ggraph(graph,layout="fr")+
        ggraph::geom_edge_link()+
        ggraph::geom_node_label(mapping = aes(label=label))
    ```