ggplot中的Rscript无效字体类型

Dav*_*vid 5 r ggplot2 rscript

我有一个使用非标准字体生成 ggplot 的简短脚本(请参阅下面的 MWE)。

如果我在 R(即 RStudio)中运行脚本,一切都按预期工作,并且我看不到任何错误。

当我使用命令行运行脚本时Rscript,出现错误:

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
In addition: There were 50 or more warnings (use warnings() to see the first 50)
Execution halted
Run Code Online (Sandbox Code Playgroud)

我用 执行脚本Rscript myscript.R,脚本的内容是

library(ggplot2)
theme_set(theme_light(base_family = "LM Roman 10"))
# if "base_family" is left empty, everything works with Rscript

p <- ggplot(mtcars, aes(x = wt, y = mpg)) +
  geom_point()

ggsave("myplot.pdf", p, device = cairo_pdf)
Run Code Online (Sandbox Code Playgroud)

我使用 Ubuntu 18.04.1 和 R 3.5.1。我还更新了我所有的软件包。

当我使用时,R CMD BATCH myscript.R一切正常。

临时解决方案

如果您有同样的问题(截至目前我还无法解决),我已恢复使用R CMD BATCH --vanilla myscript.R.

小智 1

我发现如果你使用 extrafont 库将所有​​系统字体导入到 R 中,往往可以解决问题。

执行此操作的简单方法是在终端中运行 R 并执行类似以下操作

$ R

R version 3.6.3 (2020-02-29) -- "Holding the Windsock"
Copyright (C) 2020 The R Foundation for Statistical Computing
Platform: x86_64-pc-linux-gnu (64-bit)

> library(extrafont)
Registering fonts with R
> extrafont::font_import()
Importing fonts may take a few minutes, depending on the number of fonts and the speed of the system.
Continue? [y/n] y

Run Code Online (Sandbox Code Playgroud)

按 Enter 键后,所有系统字体都应该被导入。

另一种可能性是您需要为 Ghostscript 设置环境变量,这可以通过在库调用后添加以下内容来完成

Sys.setenv(R_GSCMD="/usr/bin/ghostscript")
Run Code Online (Sandbox Code Playgroud)