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

Quarto/RMarkdown中ggplot自定义字体失效报错求助

问题描述

在IDE中渲染带自定义字体(如Montserrat)的ggplot图形可正常显示,但在Quarto或RMarkdown中渲染PDF格式文档时,持续报错:

Error in grid.Call.graphics(C_text, as.graphicsAnnot(x$label), x$x, x$y,  : 
  invalid font type
Calls: .main ... drawDetails -> drawDetails.text -> grid.Call.graphics

系统已安装所需字体,但Quarto/RMarkdown无法识别。示例脚本如下:

---
title: "TEST"
format: pdf
editor: visual
---

以下图形可正常渲染:
```{r echo=FALSE, message=FALSE, warning=FALSE}
library(tidyverse)

mtcars |>
  count (cyl) |>
  ggplot (aes (x = cyl, y = n)) + 
  geom_col() + 
  labs (title = "Plot 1") + 
  geom_text (aes (label = n), 
             vjust = -1)

以下图形无法正常渲染:

mtcars |>
 count (cyl) |>
 ggplot (aes (x = cyl, y = n)) + 
 geom_col() + 
 labs (title = "Plot 2") + 
 geom_text (aes (label = n), 
            vjust = -1,
            family = "Montserrat") + 
 theme (text = element_text(size = 12,  family = "Montserrat"))
# 解决方案
## 1. 用`extrafont`注册系统字体
Quarto/RMarkdown的渲染环境不会自动读取系统已安装字体,需手动注册:
- 安装并加载`extrafont`:
```r
install.packages("extrafont")
library(extrafont)
  • 导入系统字体(首次运行耗时较长):
font_import()
  • 加载字体到PDF设备:
loadfonts(device = "pdf")

将上述加载字体的代码放在ggplot代码之前,确保渲染时能识别Montserrat。

2. 用showtext直接指定字体文件

如果extrafont无效,可通过字体文件路径直接导入:

library(showtext)
font_add(family = "Montserrat", regular = "/绝对路径/Montserrat-Regular.ttf")
showtext_auto()

替换路径为你系统中Montserrat字体文件的实际位置,showtext_auto()会自动让ggplot调用该字体。

3. 切换PDF渲染引擎

Quarto默认的pdflatex对自定义字体支持有限,可切换到xelatex或lualatex,修改YAML头部:

---
title: "TEST"
format: 
  pdf:
    engine: xelatex
editor: visual
---

这两个引擎对非系统默认字体的兼容性更好,配合showtext使用效果更稳定。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 03:01:20