Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fonts not loading in showtext font_add_google

I'm trying to graph some data and my code looks like this:

library('ggplot2')
library('tidyr')
library('ggthemes')
library('showtext')

font_add_google('Syncopate', 'Syncopate')
showtext_auto()

ggplot(aes(x = X, group=1), data = glassdoor)+
  geom_line(aes(y = col1, color = 'red'))+
  geom_line(aes(y = col2, color = 'blue'))+
  geom_line(aes(y = col3, color = 'magenta'))+
  geom_line(aes(y = col4, color = 'yellow'))+
  theme(text = element_text(family = "Syncopate"))+
  ggtitle('A Long Test Title')

Syncopate is a distinctive font, seen here. But my visualization's font just looks like this (this is a test graph, ignore its overall poorness):

enter image description here

But if I load a system theme like Times New Roman, it works fine. Why aren't my google fonts loading using showtext?

Edit

Jrakru's answer works, but bear in mind that you have to run that entire code block: The new fonts will appear in a saved png file, but not in the preview window. This isn't written as a slight against the answer, but rather for others like myself who expect the fonts to show up in the RStudio console and therefore omit the ggsave and png portions of the code.

like image 459
snapcrack Avatar asked Jan 28 '23 04:01

snapcrack


1 Answers

The GitHub for showtext mentions

This example should work on most graphics devices, including pdf(), png(), postscript(), and on-screen devices such as windows() on Windows and x11() on Linux.

If you read really really hard between lines, that means, that RStudioGD graphics device is not supported. I did not see that the first few times I read it. I only know because the vignette is a little more explicit.

NOTE: Currently showtext does not work with the built-in graphics device of RStudio, hence to try the code below, it is suggested to run the code in original R console, or use other graphics devices such as x11() and windows()

see https://cran.rstudio.com/web/packages/showtext/vignettes/introduction.html

With the above knowledge, we can do this:

library('tidyr')
library('ggthemes')
library('showtext')

font_add_google("Schoolbell", "bell")
showtext_auto()

library('ggplot2')

df<- data.frame(x=1:10, y=101:110)

options("device" = "windows")

win.graph(10,10,12)

ggplot(data = df) +
  geom_line(aes(x,y))+
  theme(text = element_text(family = "bell"))+
  ggtitle('A Long Test Title')


ggsave("showtext-example.png", width = 7, height = 4, dpi = 96)

options("device" = "RStudioGD")

And Voila! enter image description here

Ps: I assumed you are a windows user.

like image 87
Jrakru56 Avatar answered Feb 12 '23 19:02

Jrakru56