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

Plotly导出含LaTeX的PDF时字体样式不一致问题求助

解决Plotly导出PDF时LaTeX文本与普通文本字体样式不一致的问题

问题核心

使用Plotly生成包含LaTeX格式的图表并导出为PDF时,LaTeX渲染的内容(如r"$LaTeX内容$")会显示为粗体,与普通文本的字体样式不统一,且尝试Orca、Kaleido引擎或SVG转PDF的方式均无法解决。

解决方案

方案1:在LaTeX代码中显式指定非粗体字体

直接在LaTeX表达式中加入\normalfont命令强制使用普通字体,覆盖默认的粗体设置:

import plotly.graph_objects as go

fig = go.Figure()
fig.add_trace(go.Scatter(
    x=[1, 2, 3, 4, 5],
    y=[2, 4, 1, 3, 5],
    mode='lines',
    name='Line'
))

fig.update_layout(
    title='This only happens on the PDF!',
    # 加入\normalfont强制普通字体
    xaxis_title=r'$\normalfont \Delta \text{ should not be bold, but it is}$',
    yaxis_title='Normal text is not bold',
)

fig.write_image('plot_fixed.pdf')

如果仅需要修正符号(如$\Delta$)的粗体,可单独对符号使用非粗体命令:

xaxis_title=r'$\mathrm{\Delta} \text{ should not be bold, but it is}$'

方案2:自定义Kaleido的MathJax配置

Kaleido使用独立的MathJax环境,可通过自定义配置文件全局取消LaTeX文本的粗体:

  1. 创建mathjax_config.js配置文件,内容如下:
MathJax.Hub.Config({
  "HTML-CSS": {
    styles: {
      // 针对MathJax渲染的所有元素设置普通字体权重
      ".MathJax_Display, .MathJax .mo, .MathJax .mi, .MathJax .mn, .MathJax .text": {
        "font-weight": "normal"
      }
    }
  }
});
  1. 在Python代码中指定Kaleido加载该配置:
import plotly.graph_objects as go
import plotly.io as pio

# 替换为你的mathjax_config.js文件路径
pio.kaleido.scope.mathjax_config = "./mathjax_config.js"

fig = go.Figure()
fig.add_trace(go.Scatter(
    x=[1, 2, 3, 4, 5],
    y=[2, 4, 1, 3, 5],
    mode='lines',
    name='Line'
))

fig.update_layout(
    title='This only happens on the PDF!',
    xaxis_title=r'$\Delta \text{ should not be bold, but it is}$',
    yaxis_title='Normal text is not bold',
)

fig.write_image('plot_fixed.pdf', engine='kaleido')

方案3:使用HTML混合文本替代纯LaTeX

Plotly的轴标题支持HTML格式,可直接用HTML设置字体样式并嵌入LaTeX:

import plotly.graph_objects as go

fig = go.Figure()
fig.add_trace(go.Scatter(
    x=[1, 2, 3, 4, 5],
    y=[2, 4, 1, 3, 5],
    mode='lines',
    name='Line'
))

fig.update_layout(
    title='This only happens on the PDF!',
    # 用HTML的style属性设置字体为普通权重
    xaxis_title='<span style="font-weight:normal;">$\Delta$ should not be bold, but it is</span>',
    yaxis_title='Normal text is not bold',
)

fig.write_image('plot_fixed.pdf')

说明

之前尝试的Plotly模板meta配置无效,是因为Kaleido/Orca等导出引擎不读取Plotly的HTML模板元信息,它们依赖独立的MathJax运行环境,因此需要针对渲染引擎单独配置。

内容的提问来源于stack exchange,提问作者David Lont

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 05:07:15