0

I have added a font to my ggplot2-plot, and it works perfectly when viewed in RStudio's plot viewer. However, when I try to save the plot as a PDF, NO text at all is printed (see code and pictures below):

df <- data.frame(x = c(1:10), y = c(1:10)) # Dummy data 

plot <- ggplot(df, aes(x, y)) + # Dummy plot
   geom_point() +
   labs(title = "Correct font in R, NO fonts at all in pdf :-(") +
   theme(text = element_text(family = "latex"))

Then I try to ggsave() the plot with the following code:

 ggsave("df_plot.pdf", 
   plot = plot, 
   device = "pdf", 
   dpi = 320)

But I get an error message:

Error in grid.Call.graphics(C_text, as.graphicsAnnot(x$label), x$x, x$y, : invalid font type

Below is the plot with the correct fonts (in RStudio) + the plot that is written to my pdf file (with no fonts at all):

Plot with correct font Plot witn NO text

What am I missing here? I've tried various stuff with the extrafont package, but the pdfs don't print the fonts there either (if something is printed, its just the default fonts).

markus
  • 25,843
  • 5
  • 39
  • 58
persboe
  • 71
  • 1
  • 5
  • https://stackoverflow.com/questions/28746938/ggsave-losing-unicode-characters-from-ggplotgridextra/28747843#28747843 – Shiran Cohen Jul 23 '21 at 08:21

2 Answers2

0

Actually, ggsave() appears to work fine for me. The error is actually adding the theme(text = element_text(family = "latex")) to the plot.

Adjusting the example a little bit,

df <- data.frame(x = c(1:10), y = c(1:10)) # Dummy data 

plot <- ggplot(df, aes(x, y)) + # Dummy plot
  geom_point() +
  labs(title = "Correct font in R, NO fonts at all in pdf :-(")  

ggsave("df_plot.pdf", 
       plot = plot, 
       device = "pdf", 
       dpi = 320)
#Saving 10.7 x 8.01 in image

But,

plot +  theme(text         = element_text(size=10, family="LM Roman 10"))

produces the error you've found:

Error in grid.Call(C_textBounds, as.graphicsAnnot(x$label), x$x, x$y, : polygon edge not found.

This question has already been answered here: Error in grid.Call(L_textBounds, as.graphicsAnnot(x$label), x$x, x$y, : Polygon edge not found

Do these suggestions work for you?

phargart
  • 655
  • 3
  • 14
0

you may consider using the extrafont package:

library(tidyverse)
library(extrafont)
fonts()
df <- data.frame(x = c(1:10), y = c(1:10)) # Dummy data 
windowsFonts(Calibri = windowsFont("Calibri"))
plot <- ggplot(df, aes(x, y)) + # Dummy plot
  geom_point() +
  labs(title = "Correct font in R, NO fonts at all in pdf :-(") +
  theme(text = element_text(size=15, family= "Tw Cen MT Condensed Extra Bold"))



ggsave("df_plot.pdf", 
       plot = plot, 
       device = cairo_pdf, 
       dpi = 320)

enter image description here

Iman
  • 2,224
  • 15
  • 35