首页 > 解决方案 > 使用 ggplot2 对象和自定义字体从终端运行 R 脚本(字体类型无效)

问题描述

我有一个在 R 和 RStudio 中运行良好的脚本,但是当我Rscript mycode.R在终端(macOS)中运行时,它返回以下错误:

Error in grid.Call.graphics(C_text, as.graphicsAnnot(x$label), x$x, x$y,  :
  invalid font type
Calls: stocks_report ... drawDetails -> drawDetails.text -> grid.Call.graphics
Execution halted

我知道它正在发生,因为我使用了lares::theme_lares2()将绘图字体设置为“Arial Narrow”的函数。但是,为什么通过终端运行会出现问题?

可重复的小例子。这段代码运行得很好。您可以将其保存到mycode.R文件中。

library(ggplot2)
library(lares) # devtools::install_github("laresbernardo/lares")
data(diamonds)
ggplot(diamonds, aes(cut, price)) + geom_boxplot() + theme_lares2()

尝试运行Rscript mycode.R,将返回相同的错误。

PS:请耐心安装lares库......它有很多依赖项。谢谢!:)

标签: rmacosterminalcommand

解决方案


如果这是您的代码,那么这可能是因为您没有告诉 R 将您的绘图输出到文件中。这很好,因为它会在 Rstudio 中自动绘制它,但在命令行中没有图形。我会尝试在此处添加一些保存图形的方式

pdf("where_file.pdf")
ggplot(diamonds, aes(cut, price)) + geom_boxplot() + theme_lares2()
dev.off()

推荐阅读