You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

extrafont R包无法更改ggplot2绘图字体的问题求助

解决ggplot2无法应用Latin Modern Roman字体的问题

可能的原因及解决步骤

1. 确认字体注册正确性

首先运行以下代码,确认LM Roman 10已正确注册到Windows字体列表:

windowsFonts()
# 或查看完整字体表,筛选目标字体
fonttable() %>% filter(grepl("LM Roman", FontName))

如果找不到目标字体,重新执行字体导入并重启R会话:

extrafont::font_import(recursive = TRUE, pattern = "lmroman", prompt = FALSE)
# 重启R后重新加载字体
library(extrafont)
loadfonts(device = "win")

2. 修正ggplot2的字体调用方式

extrafont在Windows下与ggplot2配合时,有时需要显式映射字体别名:

# 为目标字体设置别名
windowsFonts(LMRoman = windowsFont("LM Roman 10"))

# 绘图时使用别名指定字体
plot1 + 
  geom_bar() + 
  theme(text = element_text(size = 10, family = "LMRoman"))

3. 换用更稳定的showtext包(推荐)

如果extrafont仍不生效,试试showtext包,它对Windows字体的支持更可靠:

install.packages("showtext")
library(showtext)
library(ggplot2)

# 导入已安装的Latin Modern Roman字体(替换为实际字体文件名)
font_add("LM Roman 10", "lmroman10-regular.ttf")
showtext_auto() # 开启自动字体应用

# 绘制图形
plot1 + 
  geom_bar() + 
  theme(text = element_text(size = 10, family = "LM Roman 10"))

4. 验证字体是否生效

可以通过简单文本标注测试字体加载情况:

ggplot() + 
  annotate("text", x = 1, y = 1, label = "Test Latin Modern Roman", family = "LM Roman 10") +
  theme(text = element_text(family = "LM Roman 10"))

内容的提问来源于stack exchange,提问作者tangypancake4512

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 02:00:12