在ggiraph的 opts_tooltip CSS中无法使用通过sysfonts::font_add新增的字体

前端开发 2026-07-10

我在 ggiraph 上遇到了困难,具体来说,是在 opts_tooltip 字体选项上。

我的目标是为工具提示使用一种新字体,但我找不到实现的方法。我已经查看并尝试过一些选项,像这个帖子 为什么在ggiraph中不能使用ggplot2能识别的系统字体? 或这个帖子 在ggiraph 0.7 (R) 中设置工具提示字体,但在我的情况下都不起作用。

这是我的会话信息

R version 4.1.0 (2021-05-18)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 22631)

Matrix products: default

locale:
[1] LC_COLLATE=Italian_Switzerland.1252  LC_CTYPE=Italian_Switzerland.1252    LC_MONETARY=Italian_Switzerland.1252
[4] LC_NUMERIC=C                         LC_TIME=Italian_Switzerland.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
 [1] extrafont_0.20    stringr_1.4.0     showtext_0.9-5    showtextdb_3.0    sysfonts_0.8.8    patchwork_1.3.1   themeustat_0.0.4 
 [8] targets_1.10.1    gibr_0.0.5        ggplot2_4.0.2     ggiraph_0.9.6     reshape2_1.4.4    data.table_1.14.8 dplyr_1.1.4      

loaded via a namespace (and not attached):
 [1] jsonlite_1.8.4          viridisLite_0.4.0       S7_0.2.1                cartography_3.0.0       sp_1.4-5               
 [6] base64url_1.4           fontLiberation_0.1.0    yaml_2.2.1              ggrepel_0.9.3           gdtools_0.5.0          
[11] Rttf2pt1_1.3.9          lattice_0.20-44         pillar_1.11.0           backports_1.2.1         glue_1.4.2             
[16] extrafontdb_1.0         digest_0.6.27           RColorBrewer_1.1-2      plyr_1.8.6              htmltools_0.5.5        
[21] fontBitstreamVera_0.1.1 pkgconfig_2.0.3         magick_2.7.4            purrr_1.1.0             scales_1.4.0           
[26] processx_3.5.2          svglite_2.2.1           secretbase_1.0.1        fontquiver_0.2.1        tibble_3.3.0           
[31] proxy_0.4-26            generics_0.1.0          farver_2.1.0            withr_3.0.2             widgetframe_0.3.1      
[36] cli_3.6.1               magrittr_2.0.1          evaluate_1.0.4          ps_1.9.0                fs_1.5.2               
[41] MASS_7.3-54             xml2_1.3.3              class_7.3-19            textshaping_0.3.6       tools_4.1.0            
[46] lifecycle_1.0.3         callr_3.7.0             kableExtra_1.4.0        compiler_4.1.0          e1071_1.7-8            
[51] systemfonts_1.3.2       rlang_1.1.1             classInt_0.4-3          units_0.7-2             grid_4.1.0             
[56] dichromat_2.0-0         rstudioapi_0.13         htmlwidgets_1.5.4       crosstalk_1.1.1         igraph_2.1.4           
[61] labeling_0.4.2          rmarkdown_2.22          gtable_0.3.6            codetools_0.2-18        DBI_1.1.1              
[66] schedeustat_0.0.6.7     R6_2.5.1                knitr_1.43              utf8_1.2.2              fastmap_1.1.0          
[71] rgeos_0.5-7             tarchetypes_0.13.0      KernSmooth_2.23-20      stringi_1.7.4           parallel_4.1.0         
[76] Rcpp_1.1.1              vctrs_0.6.4             sf_1.0-2                leaflet_2.0.4.1         tidyselect_1.2.0       
[81] xfun_0.53

这是使用“sysfonts”包的示例代码

library(ggplot2)

iris$Year <- seq(1951, 2000, 1)

tab_01 <- iris[, c("Year", "Species", "Sepal.Length")]

graph_01 <- ggplot(tab_01, 
                            aes(x = Year, 
                                y = Sepal.Length, 
                                color = factor(Species), 
                                group = Species)) +
  geom_line_interactive(linewidth = 0.5, 
                        data_id = factor(tab_01$Species),
                        hover_nearest = FALSE) +
  geom_point_interactive(size = 1,
                         data_id = factor(tab_01$Species),
                         tooltip = paste0(tab_01$Year,", ", factor(tab_01$Species), ": ", tab_01$Sepal.Length),
                         hover_nearest = FALSE) +
  labs(title = "This is the title of the graph the use the right font, from 1950 to 2000", 
                size = 10, 
                y = NULL,
                caption = "This is the caption of the graphic with the right font") +
  theme(axis.text.x = element_text(angle = 90, 
                                            vjust = 0.5, 
                                            hjust = 1)) +
  theme(text = element_text(family = "Gothic_condensed",
                                     size = 10))

graph_01


# Add the new font
download.file("https://github.com/AllThingsSmitty/fonts/raw/refs/heads/master/TradeGothicLtCondensed18/TradeGothicLTStd-Cn18.otf", "TradeGothicLTStd-Cn18.otf", mode = "wb")
sysfonts::font_add(family = "Gothic_condensed", regular = "TradeGothicLTStd-Cn18.otf")

#Create "css" option for the tooltip

tooltip_css <- "
  padding: 10px;
  border-radius: 5px;
  font-family: 'Gothic_condensed';
  font-size: 15px;
  box-shadow: 0px 0px 10px rgba(0,0,0,0.5)"


# Reload the graphic with "ggiraph" package
# The title, the caption and labels font is the right one, but not the one of the tooltip

graph_02 <- ggiraph::girafe(ggobj = graph_01,
                            options = list(opts_tooltip(css = tooltip_css, use_fill = TRUE),
                                           opts_hover(css = "stroke-width:2;"),   
                                           opts_hover_inv(css = "opacity:0.3;")))

graph_02

我也尝试了你在上文提到的线程中的 systemfonts 方案,但结果相同

font_name <- "Gothic_import"

fonts <- systemfonts::system_fonts()

font_info <- fonts[grepl("^Trade", fonts$family), c("path", "index", "name", "family")]

font_info

#path                                                  index name                  family   
#<chr>                                                 <int> <chr>                 <chr>    
#  1 "C:\\...\\Windows\\Fonts\\Trade Gothic LT.ttf"     0 TradeGothicLT         TradeGot~
#  2 "C:\\...\\Windows\\Fonts\\Trade Gothic LT Std Condensed No. 18.otf"     0 TradeGothicLTStd-Cn18 Trade Go~

font_info_select <- font_info[2, ]

systemfonts::register_font(font_name,
                           plain = list(font_info_select $path, font_info_select $index))

tooltip_css <- "
  padding: 10px;
  border-radius: 5px;
  font-family: 'Gothic_import';
  font-size: 15px;
  box-shadow: 0px 0px 10px rgba(0,0,0,0.5)"

graph_02 <- ggiraph::girafe(ggobj = graph_01,
                            options = list(opts_tooltip(css = tooltip_css, use_fill = TRUE),
                                           opts_hover(css = "stroke-width:2;"),   
                                           opts_hover_inv(css = "opacity:0.3;")))

graph_02

如何在 ggiraph::girafe 中使用像 TradeGothicLTStd-Cn18.otf 这样的自定义字体?

解决方案

girafe 会生成一个HTML小部件。要添加自定义字体,你需要让这个小部件能够访问你的字体。因此,通常的做法是通过 gdtools::gfontHtmlDependency 将你的字体作为Google字体依赖来添加。要使其工作,字体族名称需要在Google Fonts上可用,例如 “Special Gothic Condensed One”,并且你在ggplot2中设置的font-family也需要与之相同,即 "Special Gothic Condensed One"。

ggiraph::girafe(
  ggobj = ggplot2::ggplot(mtcars) +
    ggplot2::geom_point(ggplot2::aes(x = wt, y = qsec, color = disp)) +
    ggplot2::labs(title = "Custom font is used here") + ggplot2::theme(plot.title = ggplot2::element_text(family = "Special Gothic Condensed One",size = 24)
  ),
  check_fonts_registered = TRUE,
  check_fonts_dependencies = TRUE,
  dependencies = list(gdtools::gfontHtmlDependency(family = "Special Gothic Condensed One"))
)

遗憾的是,你所期望的字体 Trade Gothic LT Std Condensed No. 18.otf 在Google字体中不可用。仍然可以通过在 CSS 中使用 @font-face 将字体注册为可用来添加字体。如果你不这样做,你在 tooltip_css 中的 font-family: 'Gothic_condensed'; 将会被直接忽略。注:如果我不添加依赖,上面的代码会给出一个警告,因为我设置了 check_fonts_dependencies = TRUE

完整可运行代码

library(ggplot2)
library(ggiraph)
library(htmltools)

font_name <- "Gothic_condensed"

download.file("https://github.com/AllThingsSmitty/fonts/raw/refs/heads/master/TradeGothicLtCondensed18/TradeGothicLTStd-Cn18.otf", "TradeGothicLTStd-Cn18.otf", mode = "wb")
sysfonts::font_add(family = font_name, regular = "TradeGothicLTStd-Cn18.otf")


iris$Year <- seq(1951, 2000, 1)
tab_01 <- iris[, c("Year", "Species", "Sepal.Length")]

graph_01 <- ggplot(tab_01, 
                   aes(x = Year, 
                       y = Sepal.Length, 
                       color = factor(Species), 
                       group = Species)) +
  geom_line_interactive(linewidth = 0.5, 
                        data_id = factor(tab_01$Species),
                        hover_nearest = FALSE) +
  geom_point_interactive(size = 1,
                         data_id = factor(tab_01$Species),
                         tooltip = paste0(tab_01$Year,", ", factor(tab_01$Species), ": ", tab_01$Sepal.Length),
                         hover_nearest = FALSE) +
  labs(title = "This is the title of the graph the use the right font, from 1950 to 2000", 
       size = 10, 
       y = NULL,
       caption = "This is the caption of the graphic with the right font") +
  theme(axis.text.x = element_text(angle = 90, 
                                   vjust = 0.5, 
                                   hjust = 1)) +
  theme(text = element_text(family = font_name,
                            size = 10))

graph_01

tooltip_css <- "
  padding: 10px;
  border-radius: 5px;
  font-family: 'Gothic_condensed';   
  font-size: 15px;
  box-shadow: 0px 0px 10px rgba(0,0,0,0.5)"

htmltools::tagList(
  tags$style(
    sprintf(
      '@font-face {
         font-family: "%s"; /* name of your font-family */
         src: url("https://raw.githubusercontent.com/AllThingsSmitty/fonts/refs/heads/master/TradeGothicLtCondensed18/TradeGothicLTStd-Cn18.otf") format("opentype");
       }',
      font_name
    )
  ), girafe(ggobj = graph_01, options = list(opts_tooltip(css = tooltip_css)))
) |> browsable()

给出

res

站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章