rggplot2cowplotextrafont

Using `extrafont` with `cowplot`: font width unknown for character error


I'm trying to use a font in ggplot that I can only get through the extrafont package. When I then want to combine multiple plots using the cowplot package, I always a large number of errors of the sort:

46: In grid.Call(C_textBounds, as.graphicsAnnot(x$label),  ... :
  font width unknown for character 0x65
47: In grid.Call(C_textBounds, as.graphicsAnnot(x$label),  ... :
  font width unknown for character 0x63
48: In grid.Call(C_textBounds, as.graphicsAnnot(x$label),  ... :
  font width unknown for character 0x69
49: In grid.Call(C_textBounds, as.graphicsAnnot(x$label),  ... :
  font width unknown for character 0x65
50: In grid.Call(C_textBounds, as.graphicsAnnot(x$label),  ... :
  font width unknown for character 0x73

Note the package does actually produce the output (ie a plot side-by-side) but the error messages concern me.

What I tried so far:

I have extrafont and extrafontdb as well as cowplot installed.

Here an example of my use:

library(tidyverse)
library(extrafont)
library(cowplot)
library(palmerpenguins)
data(penguins)


penguins %>% 
  select(year, flipper_length_mm,species) %>% 
  ggplot(aes(x=year,y=flipper_length_mm,fill=species)) +
  geom_col() + 
  labs(title = "First Plot") + 
  theme(text = element_text(family = "Georgia")) -> plot1


penguins %>% 
  select(year, bill_length_mm,species) %>% 
  ggplot(aes(x=year,y=bill_length_mm,fill=species)) +
  geom_col() + 
  labs(title = "Second Plot") + 
  theme(text = element_text(family = "Georgia")) -> plot2

cowplot::plot_grid(plot1,plot2)

enter image description here


Solution

  • Just quickly answering this thanks to Claus Wilke's answer in the comments:

    It is necessary to set the null device. You may have to install the development version for this to fully work (it did work fine for me!).

    The short answer:

    set_null_device(cairo_pdf)
    cowplot::plot_grid(plot1,plot2)
    

    And the error messages disappear. Using set_null_device("png") also worked for me, but given that I'm aiming to save a PDF, this is the safer option according to Claus.

    In full:

    library(tidyverse)
    library(extrafont)
    library(cowplot)
    library(palmerpenguins)
    data(penguins)
    
    
    penguins %>% 
      select(year, flipper_length_mm,species) %>% 
      ggplot(aes(x=year,y=flipper_length_mm,fill=species)) +
      geom_col() + 
      labs(title = "First Plot") + 
      theme(text = element_text(family = "Georgia")) -> plot1
    
    
    penguins %>% 
      select(year, bill_length_mm,species) %>% 
      ggplot(aes(x=year,y=bill_length_mm,fill=species)) +
      geom_col() + 
      labs(title = "Second Plot") + 
      theme(text = element_text(family = "Georgia")) -> plot2
    
    
    set_null_device(cairo_pdf)
    cowplot::plot_grid(plot1,plot2)