如何设置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
相关产品推荐
相关产品推荐

