在geom_text_repel()中使用AvantGarde字体报错,寻求解决办法
在
geom_text_repel中使用AvantGarde字体报错的问题及解决方法 问题概述
希望在geom_text_repel中使用AvantGarde字体族,但运行代码时出现错误,且提示找不到该字体。
最小复现代码
library(ggrepel) p <- ggplot(mtcars, aes(wt, mpg, label = rownames(mtcars), colour = factor(cyl))) + geom_point() p + geom_text_repel(family = 'AvantGarde')
报错信息
运行代码后输出错误:
Error in grid.Call(C_textBounds, as.graphicsAnnot(x$label), x$x, x$y, : polygon edge not found In addition: There were 12 warnings (use warnings() to see them)
同时出现核心警告:
1: In grid.Call(C_textBounds, as.graphicsAnnot(x$label), ... : no font could be found for family "AvantGarde"
环境版本信息
R会话sessionInfo()输出:
R version 4.1.3 (2022-03-10) Platform: x86_64-apple-darwin17.0 (64-bit) Running under: macOS 13.2.1 Matrix products: default LAPACK: /Library/Frameworks/R.framework/Versions/4.1/Resources/lib/libRlapack.dylib locale: [1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8 attached base packages: [1] stats graphics grDevices utils datasets methods base other attached packages: [1] ggrepel_0.9.2.9999 ggplot2_3.4.1 loaded via a namespace (and not attached): [1] Rcpp_1.0.10 fansi_1.0.4 withr_2.5.0 dplyr_1.1.0 [5] utf8_1.2.3 grid_4.1.3 R6_2.5.1 lifecycle_1.0.3 [9] gtable_0.3.3 magrittr_2.0.3 scales_1.2.1 pillar_1.9.0 [13] rlang_1.1.0 cli_3.6.1 farver_2.1.1 rstudioapi_0.14 [17] generics_0.1.3 vctrs_0.6.1 labeling_0.4.2 tools_4.1.3 [21] glue_1.6.2 munsell_0.5.0 compiler_4.1.3 pkgconfig_2.0.3 [25] colorspace_2.1-0 tidyselect_1.2.0 tibble_3.2.1
尝试R中其他可用字体后,问题仍未解决。
解决方法
1. 确认系统是否安装目标字体
警告核心是找不到AvantGarde字体,先检查macOS系统是否已安装:
- 打开「字体册」应用,搜索"AvantGarde",若未找到,需先安装该字体文件。
2. 使用字体的准确名称
字体的显示名称和代码中调用的名称可能不一致,用extrafont包查看系统可用字体的准确名称:
# 安装并加载extrafont install.packages("extrafont") library(extrafont) # 导入系统所有字体 font_import() # 查看所有可用字体列表 fonts()
在输出列表中找到AvantGarde对应的准确名称(比如可能是ITC Avant Garde Gothic或AvantGarde Book),替换代码中family参数的值。
3. 注册字体并配置绘图设备
导入字体后,需注册到R的绘图设备中:
# 针对macOS的quartz设备加载字体 loadfonts(device = "quartz") # 重新运行绘图代码,使用准确的字体名称 p + geom_text_repel(family = "ITC Avant Garde Gothic")
如果是导出PDF,将device参数改为"pdf"。
4. 测试系统默认字体排除问题
如果以上方法无效,先使用macOS默认支持的字体(如Helvetica)测试,确认绘图逻辑本身无问题:
p + geom_text_repel(family = "Helvetica")
若此代码能正常运行,说明问题确实出在AvantGarde字体的识别或安装环节。
内容的提问来源于stack exchange,提问作者Damien Georges
相关产品推荐
相关产品推荐

