R中showtext添加的字体重启后无法使用的问题求助
解决showtext自定义字体加载问题
问题原因
你的警告完全是因为新R会话里没有重新注册自定义字体——showtext的font_add()是会话级别的操作,只会把字体注册到当前R环境中,关闭R后就会失效,所以每次启动新脚本(新会话)都需要重新执行font_add()。
正确操作流程
每次新脚本里必须按顺序执行以下步骤:
library(showtext) # 关键:必须重新注册字体到当前会话 font_add(family = "Myriad Pro", regular = "C:/USER/Downloads/Myriad Pro Regular.ttf") showtext_auto() library(ggplot2) ggplot(mtcars, aes(y = hp, x = mpg)) + geom_line() + theme(text = element_text(family = "Myriad Pro"))
简化操作:自动加载字体
不想每次手动写font_add()?可以把字体注册代码放到R的启动配置文件.Rprofile里,让R每次启动自动执行:
- 打开配置文件:
file.edit("~/.Rprofile") - 添加以下内容(确保字体路径正确):
if (requireNamespace("showtext", quietly = TRUE)) { library(showtext) font_add(family = "Myriad Pro", regular = "C:/USER/Downloads/Myriad Pro Regular.ttf") showtext_auto() } - 保存文件后重启R,之后新脚本里直接调用ggplot指定字体即可,无需重复加载字体代码。
额外提示
如果你的字体有多种字重(如粗体、斜体),可以一次性在font_add()里配置:
font_add( family = "Myriad Pro", regular = "C:/USER/Downloads/Myriad Pro Regular.ttf", bold = "C:/USER/Downloads/Myriad Pro Bold.ttf", italic = "C:/USER/Downloads/Myriad Pro Italic.ttf" )
内容的提问来源于stack exchange,提问作者Moritz Schwarz
相关产品推荐
相关产品推荐

