代码之家  ›  专栏  ›  技术社区  ›  David

Rscript ggplot中的字体类型无效

  •  1
  • David  · 技术社区  · 7 年前

    我有一个使用非标准字体生成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
    

    我使用 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)
    

    我使用Ubuntu18.04.1和R3.5.1。我还更新了我所有的软件包。

    R CMD BATCH myscript.R 一切都很好。

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

    0 回复  |  直到 5 年前
        1
  •  0
  •   TheLazyHatGuy    5 年前

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

    实现这一点的简单方法是在terminal中运行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
    
    

    在按下enter键后,应导入所有系统字体。

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

    Sys.setenv(R_GSCMD="/usr/bin/ghostscript")
    
    推荐文章