如何让ggplot2字体自动匹配Rmd/Qmd HTML主题字体?
自动匹配ggplot2字体与HTML主题字体的实现方案
步骤1:获取当前文档的主题
在文档编织阶段,可直接读取YAML元数据获取主题配置:
- R Markdown:用
rmarkdown::metadata$theme提取YAML中指定的主题名称(如yeti、united) - Quarto:用
quarto::quarto_metadata$theme获取主题参数
步骤2:获取主题的字体变量(替代手动查找样式表)
针对yeti、united这类Bootswatch主题,推荐用bslib包直接提取主题内置的字体变量,比手动解析CSS更高效可靠:
- 通过
bslib::bs_theme(theme = 主题名称)生成对应主题对象 - 用
bslib::bs_theme_get_variables(theme_obj, "font-family-base")直接获取正文字体族配置
完整的magic_function_to_retrieve_current_font()实现
magic_function_to_retrieve_current_font <- function() { # 检测文档类型并获取主题 if (requireNamespace("quarto", quietly = TRUE) && quarto::quarto_is_running()) { theme_name <- quarto::quarto_metadata$theme } else if (requireNamespace("rmarkdown", quietly = TRUE)) { theme_name <- rmarkdown::metadata$theme } else { stop("仅支持R Markdown或Quarto文档") } # 处理未指定主题的默认情况 theme_name <- theme_name %||% "default" # 获取主题字体变量 theme_obj <- bslib::bs_theme(theme = theme_name) font_family <- bslib::bs_theme_get_variables(theme_obj, "font-family-base") # 提取第一个字体条目并清理格式 font_family <- gsub('["\\s]', '', font_family) strsplit(font_family, ",")[[1]][1] }
使用示例
在文档中调用函数获取字体后,直接应用到ggplot2:
library(ggplot2) current_font <- magic_function_to_retrieve_current_font() ggplot(mtcars, aes(wt, mpg)) + geom_point() + theme(text = element_text(family = current_font))
注意事项
- 确保文档使用
bslib支持的Bootswatch主题,自定义CSS主题可通过bslib::bs_theme_add_css()加载后再提取字体 - 函数必须在编织阶段运行,交互式环境无法读取文档元数据
内容的提问来源于stack exchange,提问作者teunbrand
相关产品推荐
相关产品推荐

