我无法在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
我已经导入了此处所示的所有字体。有什么问题吗?
其他答案没有解决我的问题(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:WindowsFonts
文件夹中的文件。为了解决这个问题,我用install.packages("extrafontdb")
重置了我的extrafonts::fonttable()
,以便清除对不同位置字体的引用。
关于保存的编辑:
深入兔子洞。储蓄是一个额外的挑战。为了extrafont::loadfonts(device="pdf")
,我必须确保我的extrafont::fonttable()
中没有字体具有相同的家族名称和粗体/斜体状态。我编辑了extrafont:::fonttable_file()
以解决家族中任何重复的粗体/斜体字体。使用Roboto Condensed,我将浅色字体的字体家族重命名为"Roboto Condensed light"。
然后使用ggsave(device="pdf")
进行保存。以acrobat打开文件时,字体显示不正确。我试着用ghostscript嵌入字体,并使用cairo.pdf设备。最简单、功能最强大的解决方案是在Illustrator中打开.pdf文件(字体在那里显示得很好),然后立即将其重新保存为.pdf。
编辑关于保存的2:
保存为.eps是在illustrator和acrobat中保存该文件的唯一方法。结果是完美的。ggsave(g, file="Figure.eps", fonts=c("FONT FAMILIES USED", "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)
我会尝试"
windowsFonts(Times=windowsFont("TT Times New Roman"))
在执行此操作时,您可以显式指定Windows字体映射。
您必须使用以下命令导入系统字体:
font_import(paths = NULL, recursive = TRUE, prompt = TRUE,pattern = NULL)
我在这里尝试了不同的解决方案,但都不适用(win10,R 3.4.3)。这就是对我有效的:
install.packages("extrafont")
library(extrafont)
loadfonts(device = "win")
不管我是在library(ggplot2)
之前还是之后做的
来源:
- https://cran.r-project.org/web/packages/extrafont/extrafont.pdf
- 更改ggplot2中的字体