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):
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.
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!
Ps: I assumed you are a windows
user.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With