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

如何设置Bokeh中LaTeX数学符号元素的字体?

解决Bokeh中LaTeX数学文本与默认字体不一致的问题

Bokeh默认用MathJax渲染LaTeX数学文本,其默认字体是类似Times的衬线字体,和Bokeh全局的Helvetica无衬线字体不统一。要解决这个问题,需通过配置MathJax切换字体,以下是两种可行方案:

方案一:全局配置MathJax字体(适用于所有图表)

在启动Bokeh应用或生成图表前,修改MathJax配置,指定使用与Helvetica匹配的开源替代字体(如TeX Gyre Heros):

from bokeh.settings import settings

# 配置MathJax使用TeX Gyre Heros字体
settings.mathjax_config = """
MathJax.Hub.Config({
  "HTML-CSS": {
    preferredFont: "TeX",
    availableFonts: ["TeX Gyre Heros"],
    webFont: "TeX Gyre Heros",
    matchFontHeight: false
  },
  SVG: {
    font: "TeX Gyre Heros"
  }
});
"""

方案二:单图表注入MathJax配置(仅作用于当前图表)

通过CustomJS回调在图表加载时动态配置MathJax,无需全局修改:

from bokeh.plotting import figure, show
from bokeh.models import CustomJS

# 创建图表
p = figure(
    x_axis_label=r'$$\text{Unified font with math formatting }M_{2}^{3}$$',
    y_axis_label=r'Normal bokeh font',
    width=400, height=400
)
p.line(x=[0,1,2,3], y=[4,6,5,7])

# 注入MathJax配置的JS回调
callback = CustomJS(code="""
  MathJax.Hub.Config({
    "HTML-CSS": {
      preferredFont: "TeX",
      availableFonts: ["TeX Gyre Heros"],
      webFont: "TeX Gyre Heros",
      matchFontHeight: false
    },
    SVG: {
      font: "TeX Gyre Heros"
    }
  });
  MathJax.Hub.Queue(["Typeset", MathJax.Hub]);
""")

# 绑定到文档加载事件
p.js_on_event('document_ready', callback)

show(p)

关键说明

  • Bokeh的axis_label_text_font等文本样式属性无法作用于MathJax渲染的LaTeX内容,这类内容由MathJax独立处理,必须通过其自身配置修改字体。
  • TeX Gyre Heros是Helvetica的开源兼容字体,能保证与Bokeh默认字体视觉一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 04:25:09