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

为何ggplot2识别的Segoe UI字体在ggiraph中无法正常使用?

问题

我尝试用公司自定义的ggplot主题,通过ggiraph生成交互式图表。主题中指定的字体定义如下:

font_light <- "Segoe UI Semilight"

主题调用字体的代码:

# font_import() # 已执行过一次
loadfonts(device = "win") # 每次会话都需执行

theme_org <- function() {
   theme(
      # 文本元素
      plot.subtitle = element_text(
        family = font_light,
        size = 11,
        hjust = 0,
        margin = margin(b = 10)
      )
   )
}

用这个主题生成常规ggplot图表完全正常,但把ggplot对象传入girafe()时,出现如下错误:

Error in `girafe()`:
! Font family 'Segoe UI Semilight' has not been found on your system or is not registered.
ℹ You can use a google font with `gdtools::register_gfont()`.
ℹ You can use any font with `systemfonts::register_font()`.

我系统中的Segoe字体列表(通过systemfonts::system_fonts()过滤得到)里确实包含Segoe UI Semilight,其中该字体的weight字段为NA。

尝试注册字体后,Segoe UI Semibold可以正常生效,但Segoe UI Semilight还是不行。我的注册代码如下:

# 注册字体
fonts <- systemfonts::system_fonts()
segoe_fonts <- fonts %>% filter(grepl("Segoe", family))

font_light <- "Segoe UI Semilight"
font_semi <- "Segoe UI Semibold"

font_light_info <- segoe_fonts %>% filter(name == "SegoeUI-Semilight")
font_semi_info <- segoe_fonts %>% filter(name == "SegoeUI-Semibold")

systemfonts::register_font(
  font_light,
  plain = list(font_light_info$path, font_light_info$index)
)
systemfonts::register_font(
  font_semi,
  plain = list(font_semi_info$path, font_semi_info$index)
)

执行后,图表的副标题变回默认字体,但图例标题成功应用了Semibold字体,请问该怎么解决Semilight的问题?

解决方案

问题出在Segoe UI Semilight的weight字段为NA,ggiraph依赖的systemfonts无法正确识别这个字体的字重,导致注册后无法生效。可以通过以下步骤修复:

  • 明确指定字体的字重参数
    在注册Segoe UI Semilight时,手动指定weight参数为"light"(对应字重数值300),让systemfonts能正确识别:
# 重新注册Segoe UI Semilight,指定字重
systemfonts::register_font(
  name = font_light,
  plain = list(
    path = font_light_info$path,
    index = font_light_info$index,
    weight = "light" # 或直接用数值300
  )
)
  • 统一字体加载方式,避免冲突
    你同时使用了loadfonts(device = "win")(extrafont包)和systemfonts注册字体,两者的字体识别机制不同,可能导致冲突。建议在使用ggiraph时,仅依赖systemfonts注册字体,注释掉loadfonts(device = "win"),确保ggiraph使用的是systemfonts注册的字体族名称。

  • 验证字体注册状态
    执行以下代码确认字体已正确注册:

# 检查已注册的字体
systemfonts::registered_fonts() %>% filter(grepl("Segoe UI Semilight", name))

如果能看到对应的条目,说明注册成功。

  • 重启R会话后重新运行
    字体注册有时需要重启R会话才能完全生效,重启后重新执行字体注册代码和图表生成代码。

按照以上步骤操作后,Segoe UI Semilight应该能在ggiraph生成的交互式图表中正常生效,副标题也会正确应用该字体。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 07:54:55