字体未加载到 showtext font_add_google

Fonts not loading in showtext font_add_google

我正在尝试绘制一些数据,我的代码如下所示:

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 是一种独特的字体,见 here。但是我的可视化字体是这样的(这是一个测试图,忽略它的整体劣势):

但是如果我加载像 Times New Roman 这样的系统主题,它就可以正常工作。为什么我的 google 字体没有使用 showtext 加载?

编辑

Jrakru 的回答有效,但请记住,您必须 运行 整个代码块:新字体将出现在已保存的 png 文件中,但不会出现在预览中 window。这并不是对答案的轻微反对,而是针对像我这样希望字体显示在 RStudio 控制台中并因此省略代码的 ggsavepng 部分的其他人。

showtext 的 GitHub 提到了

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.

如果您在两行之间读到 真的很难,这意味着 RStudioGD 图形设备不受支持。前几次我没有看到它。我只知道因为 vignette 更明确一点。

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()

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

有了上面的知识,我们可以这样做:

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")

瞧!

Ps:我假设您是 windows 用户。

根据同一文件:https://cran.rstudio.com/web/packages/showtext/vignettes/introduction.html

在它的最底部,您可以阅读:

Compatibility with RStudio

Starting from version 0.9, showtext can work well with the RStudio graphics device (RStudioGD). Simply call showtext_auto() in the RStudio session and then the plots will be displayed correctly.

它在 RStudio 1.3.959 中对我有用