Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rscript invalid font type in ggplot

Tags:

r

ggplot2

rscript

I have a short script that produces a ggplot using a non-standard font (see MWE below).

If I run the script in R (i.e., RStudio) everything works as expected and I see no error.

When I run the script using the command line and Rscript I get the error:

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

I execute the script with Rscript myscript.R, the contents of the script is

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)

I use Ubuntu 18.04.1 with R 3.5.1. I also updated all my packages.

When I use R CMD BATCH myscript.R everything works as well.

Temporary Solution

If you have the same issue (as of now I haven't been able to solve it), I have reverted to using R CMD BATCH --vanilla myscript.R.

like image 618
David Avatar asked Nov 17 '22 19:11

David


1 Answers

I found that if you use the extrafont library to import all system fonts into R that tends to fix the problem.

The easy way to do this is to run R in terminal and do something like this

$ 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

After hitting enter, all of your system fonts should be imported.

Another possibility is that you need to set an environment variable for Ghostscript, which can be done by adding the following after your library calls

Sys.setenv(R_GSCMD="/usr/bin/ghostscript")
like image 69
TheLazyHatGuy Avatar answered Nov 19 '22 09:11

TheLazyHatGuy