【问题标题】:RMarkdown won't knit ggplot2 plot after changing font更改字体后,RMarkdown 不会编织 ggplot2 绘图
【发布时间】:2020-12-22 06:00:49
【问题描述】:

下图是在 R 中生成的(没有任何问题),使用以下代码:

library(tidyverse)
library(extrafont)
loadfonts()

x <- rexp(100)

data.frame(info = x) %>% 
ggplot() + 
geom_histogram(aes(x = info), col = "red", fill = "red", alpha = 0.5) +
theme_minimal() +
theme(text = element_text(family="LM Roman 10"))

如您所见,绘图的字体设置为“LM Roman 10”,感谢post,我能够做到这一点,它在 R 中完美运行。

但是,当我尝试使用 RMarkdown 将图像放置在 LaTeX 文档中时,出现以下错误:

Quitting from lines 10-22 (min_example.Rmd) 
Error in grid.Call.graphics(C_text, as.graphicsAnnot(x$label), x$x, x$y,  : 
  invalid font type
Calls: <Anonymous> ... drawDetails -> drawDetails.text -> grid.Call.graphics
Además: There were 50 or more warnings (use warnings() to see the first 50)
Ejecución interrumpida
    

这是min_example.Rmd的代码

---
title: "Untitled"
author: "Javier Rojas"
date: "2/9/2020"
output: pdf_document
---


```{r, echo=FALSE}

library(tidyverse)
library(extrafont)
loadfonts()

x <- rexp(100)

data.frame(info = x) %>% 
ggplot() + 
geom_histogram(aes(x = info), col = "red", fill = "red", alpha = 0.5) +
theme_minimal() +
theme(text = element_text(family="LM Roman 10"))
```

我使用的是运行 macOS High Sierra 和 R 3.6.1 的 Mac 计算机

【问题讨论】:

  • 您安装了拉丁现代字体吗?见this,说明中有答案。
  • 是的佩德罗,我有。代码在 R 中运行没有问题,当我将该代码放在 RMarkdown 块中时会出现问题

标签: r ggplot2 fonts r-markdown


【解决方案1】:

通常很容易解决。问题应该是,您的计算机中没有安装字体。

您必须下载字体的 .otf 文件,例如(https://fonts2u.com/lmroman10-regular.font) 并将其安装在您的操作系统上。

如果你不知道怎么做,就用谷歌搜索(例如“安装额外字体 Windows”),网上有很多教程。

-编辑- 我有点快 - 没有意识到问题只是来自于在 rmarkdown 中运行它。请尝试以下操作:

```{r, fig.showtext=TRUE, echo=FALSE}
library("tidyverse")
library("showtext")

x <- rexp(100)

font_add("LM Roman 10", regular = "lmroman10-regular.otf")

data.frame(info = x) %>% 
ggplot() + 
geom_histogram(aes(x = info), col = "red", fill = "red", alpha = 0.5) +
theme_minimal() +
theme(text = element_text(family="LM Roman 10"))
      
```

添加fig.showtext=TRUE、library("showtext") 和font_add("LM Roman 10", regular = "lmroman10-regular.otf") 很重要。

我刚刚将 .otf 放在我的项目文件夹中 - 但我认为您也可以给它另一个路径。

【讨论】:

  • 嗨史蒂芬!不,字体已安装。我什至可以在 Microsoft Word 中使用它。正如我所提到的,代码在 R 中运行没有问题,当我将该代码放在 RMarkdown 块中时会出现问题
  • 哦,你真的确定吗?当您尚未安装字体时,“无效字体类型”通常正是您收到的消息。当我没有安装字体时,我收到几乎相同的错误消息。虽然安装的字体没有错误(也适用于您的示例)。我也有 macOS。如果您确实安装了正确的字体,我会检查(尝试我的链接中的 .odt)。也尝试将它安装在用户下的 Mac 字体集合中。还要确保在 R 中以正确的名称引用它(添加到字体集合中)
  • 是的,我刚刚从您的链接安装了 .odt。我仍然得到同样的错误。我检查并在用户下安装了字体。您将如何在 R 中正确引用字体? loadfonts("拉丁现代罗马")?
  • 是的....但我很抱歉,我读得太快了 xD 没有 rmarkdown 没有执行它;)正如你已经说过的那样工作正常 - 等等我也会发布如何做它在 rmarkdown 中
猜你喜欢
  • 2021-03-15
  • 2020-11-25
  • 2018-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多