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

使用ggtext的element_textbox搭配Public Sans字体时字间距过近求助

问题:ggplot2中element_textbox搭配Public Sans字体导出PNG后字间距过近/重叠

用ggplot2绘图时,偏好使用ggtext包的element_textbox实现长文本自动换行,但搭配Public Sans字体时,预览面板显示正常,用ggsave()导出为PNG后出现字间距过近甚至重叠的问题。已尝试调整padding和margin参数无效,使用extrafont导入字体,且已卸载ragg避免冲突。

测试代码:

library(ggplot2)
library(ggtext)
library(extrafont)

extrafont::font_import(paths = NULL, prompt = FALSE, pattern = "PublicSans")
extrafont::loadfonts(device = "win")

ggplot(mpg, aes(displ, hwy, colour = class)) + 
  geom_point() +
  labs(
    title = "使用element_text时字间距正常...",
    caption = "...但这是一段可能会超出图表宽度的超长说明文字,所以我用element_textbox来自动换行,结果却出现了字间距过近的问题。") + 
  theme(
    text = element_text(family = "Public Sans"),
    plot.title = element_text(size = 9),
    plot.caption = ggtext::element_textbox_simple(size = 9,
                                           fill = "red")
  )

ggsave("test.png")

问题截图:
问题截图:字间距重叠


解决方案

方法1:改用systemfonts包替代extrafont导入字体

extrafont对部分字体的渲染支持有限,systemfonts能更好地适配系统字体,无需手动导入步骤:

library(ggplot2)
library(ggtext)
library(systemfonts)

ggplot(mpg, aes(displ, hwy, colour = class)) + 
  geom_point() +
  labs(
    title = "使用element_text时字间距正常...",
    caption = "...但这是一段可能会超出图表宽度的超长说明文字,所以我用element_textbox来自动换行,现在字间距正常了。") + 
  theme(
    text = element_text(family = "Public Sans"),
    plot.title = element_text(size = 9),
    plot.caption = ggtext::element_textbox_simple(size = 9, fill = "red")
  )

# 用cairo-png设备导出,优化渲染效果
ggsave("test_fixed.png", type = "cairo-png")

方法2:手动调整element_textbox的字间距参数

如果坚持使用extrafont,可通过letter_spacing和lineheight强制调整:

plot.caption = ggtext::element_textbox_simple(
  size = 9,
  fill = "red",
  letter_spacing = 0.03,  # 数值越大,字间距越宽
  lineheight = 1.1        # 调整行高避免行内重叠
)

方法3:导出时指定cairo设备

在ggsave中启用cairo渲染,改善字体导出效果:

ggsave("test_cairo.png", device = grDevices::png, type = "cairo")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 12:35:31