使用extrafont或showtext在R中导入女性和男性符号的字体,用于ggplot2。

3

我尝试在ggplot图中使用女性♀和男性♂符号。当我加载extrafont包并运行所需代码时,它不起作用(类似于这个帖子)。

我使用的是Mac OS X 10.11.6版本,并使用R for Mac OS X 3.5.2版本。

install.packages("extrafont")
library(extrafont)
extrafont::loadfonts(device="pdf")
extrafont::font_import(pattern="CALIBRI") #pattern that has the ♀ and ♂ symbols
#when I run this as font_import() alone fonts() is still empty

错误信息:

扫描 /Library/Fonts/、/System/Library/Fonts 和 ~/Library/Fonts/ 中的 ttf 文件... 从 ttf 文件中提取 .afm 文件... 在 data.frame(fontfile = ttfiles, FontName = "", stringsAsFactors = FALSE) 中出现错误: arguments imply differing number of rows: 0, 1

双重检查:

> fonts() #empty
 NULL
> fonttable() #empty
 data frame with 0 columns and 0 rows

请问有人知道为什么会出现这种情况,以及如何使它正常运行?

更新:

另外,我可以使用不同的包来加载Calibri字体(请参见 这里 中的OP)。 但是,我仍然无法在我的ggplot中显示♀和♂符号。 有建议吗?

install.packages('showtext', dependencies = TRUE)
library(showtext)
font_add_google("Montserrat", "Montserrat")
font_add_google("Roboto", "Roboto")
font_paths() 
font_files()

# syntax: font_add(family = "<family_name>", regular = "/path/to/font/file")
font_add("Calibri", "calibri.ttf")
font_families()
showtext_auto() 

这可能会有所帮助 https://dev59.com/SK3la4cB1Zd3GeqPQ7Xy#51888677 - Tung
@Tung 我试过了,但是即使我找到了字体存储在硬盘的位置,他们提供的解决方案仍然无效。 - Blundering Ecologist
1个回答

1
"showtext应该能够完成这项工作。"
library(ggplot2)
library(showtext)
showtext_auto()

female = intToUtf8(9792)
male = intToUtf8(9794)

p = ggplot() +
    annotate("text", x = 1, y = 1, label = female, size = 20) +
    annotate("text", x = 2, y = 1, label = male, size = 20) +
    theme_bw(base_family = "sans")

## On screen
x11()
print(p)

## Save to PDF
ggsave("symbol.pdf", p, width = 9, height = 6)

enter image description here


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