无法在ggplot/geom_text中更改字体

53

我无法在geom_text中设置字体。以下是我的尝试:

    labels_test<-data.frame(a=c("a","b","c"),b=c(1:3),c=c(3:1))
    # works
    ggplot () + geom_text(data=labels_test,aes(b,c,label=a),color="blue")
    # does not work: 
    ggplot () + geom_text(data=labels_test,aes(b,c,label=a),color="blue",family="Times")
    # error message:  In grid.Call.graphics(L_text, as.graphicsAnnot(x$label), x$x, x$y,:
    # Font family not found in Windows font database
我已经按照这里所示导入了所有字体。你有什么想法是仍然出了问题吗?

6
如果您先尝试使用 windowsFonts(Times=windowsFont("TT Times New Roman")),它能起作用吗? - user1317221_G
1
是的,谢谢。你应该将其发布为答案。你能解释一下吗?当我想使用不同的字体时,我是否需要在所有脚本中都这样做? - Joschi
我现在正在使用Mac,所以无法随意摆弄,但是这个链接可能会有所帮助,但主要的想法是一旦你安装了字体,就明确地将它们提供给R来使用。 - user1317221_G
您可以使用{extrafont}包批量导入字体,具体操作请参考此文章:http://blog.revolutionanalytics.com/2012/09/how-to-use-your-favorite-fonts-in-r-charts.html - Brandon Loudermilk
4个回答

40

其他回答没有解决我的问题(Windows 10)。

对于我的系统,关键是在调用library(ggplot2)之前先调用extrafont::loadfonts(device="win")

extrafont::loadfonts(device="win")
#extrafont::fonttable()
#extrafont::font_import("C:/Windows/Fonts/", pattern = "RobotoCondensed")
library(ggplot2)

常见的字体位置问题:

我之前使用extrafont::font_import()从一个随机文件夹安装了字体。因此,extrafont::fonttable()引用了我的C:\Windows\Fonts\文件夹中的文件。为了解决这个问题,我通过install.packages("extrafontdb")重置了我的extrafonts::fonttable(),以清除对不同位置字体的引用。

关于保存的编辑:

更深入的问题是保存。为了使用extrafont::loadfonts(device="pdf"),我必须确保extrafont::fonttable()中没有相同的字体家族和粗/斜体状态。我编辑了extrafont:::fonttable_file()以解决家族内的任何重复的粗/斜体字体。使用Roboto Condensed,我将轻体字的字体家族重命名为“Roboto Condensed Light”。

使用ggsave(device="pdf")保存后,文件在Acrobat中打开时字体显示不正确。我尝试嵌入字体和使用cairo_pdf设备。最简单和最实用的解决方案是在Illustrator中打开.pdf文件(字体在那里显示正常),然后立即重新保存为.pdf。

有关保存的编辑2:

保存为.eps是在Illustrator和Acrobat中都能保留文件的唯一方法。结果完美无缺。ggsave(g, file="Figure.eps", fonts=c("使用的字体家族", "Roboto Condensed", "Roboto Condensed Light"))

最终绘图代码:

这是我绘图前使用的最终设置。注释是只需要运行一次的设置命令。

# Plotting
extrafont::loadfonts(device="pdf")
extrafont::loadfonts(device="postscript")
# extrafont::font_import("C:/Windows/Fonts/", pattern = "RobotoCondensed", prompt = F)
# extrafont::fonttable()
# C:/Program Files/R/R-3.3.1/library/extrafontdb/fontmap/ - Change lights to "Roboto Condensed Light"
# After ggsave(device="pdf") or ggsave(device="eps") open and resave the file in Illustrator
library(hrbrthemes)
library(ggplot2)

2
这似乎是显而易见的,但值得补充的是:在尝试加载任何字体之前,请确保通过执行 extrafont::font_import() 来加载字体。 - Jared Wilber

38

我会尝试。

windowsFonts(Times=windowsFont("TT Times New Roman"))

这样做可以明确指定Windows字体映射。


1
那么你会如何为每个导入的字体执行此操作? - Matias Andina

20

您必须使用以下命令导入系统字体:

font_import(paths = NULL, recursive = TRUE, prompt = TRUE,pattern = NULL)

1
这实际上是问题的真正“答案”。 - skoh
7
如果你拥有大量字体,这个解决方案会花费很长时间。使用 pattern="Times" 或其他类似的东西来减少加载的字体数量。 - C8H10N4O2
这是一次性操作还是每次都必须运行的操作?在我看来,它可能只需要运行一次。 - Akhil Nair

3

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接