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

如何在Jupyter Notebooks中正确渲染含math、plot块的格式化函数文档

解决方案

处理.. math::块渲染

Jupyter和IPython支持自定义docstring渲染规则,你可以通过修改格式化器配置实现LaTeX公式自动渲染:

  1. 先安装必要依赖:pip install sphinx numpydoc
  2. 在Jupyter的cell中运行以下配置代码:
from IPython.core import formatters
from sphinx.ext.napoleon import Config, NumpyDocstring
import re

def render_math_doc(obj, p, cycle):
    raw_doc = getattr(obj, '__doc__', '')
    if not raw_doc:
        p.text(raw_doc)
        return
    # 解析numpy格式文档
    config = Config()
    doc = NumpyDocstring(raw_doc, config=config)
    rendered = str(doc)
    # 替换块级math为LaTeX格式
    math_block_pat = re.compile(r'\.\. math::\s*\n\s*(.*?)(?=\n\S|\Z)', re.DOTALL)
    rendered = math_block_pat.sub(lambda m: f'$$ {m.group(1).strip()} $$', rendered)
    # 替换行内math标记
    inline_math_pat = re.compile(r':math:`(.*?)`')
    rendered = inline_math_pat.sub(r'$\1$', rendered)
    p.text(rendered)

# 注册格式化规则
ip = get_ipython()
ip.display_formatter.formatters['text/plain'].for_type(type, render_math_doc)

配置完成后再调用函数名?就能看到公式正常渲染了。

处理.. plot::块渲染

.. plot::是Sphinx的专属绘图指令,要实现自动执行代码生成图片,可以在上面的配置基础上新增绘图逻辑:

import io
import matplotlib.pyplot as plt
from IPython.display import display, Image

def render_plot_block(rendered_text):
    plot_pat = re.compile(r'\.\. plot::\s*\n(.*?)(?=\n\S|\Z)', re.DOTALL)
    def exec_plot_code(match):
        code = match.group(1).strip()
        # 执行绘图代码
        exec(code, globals(), {})
        # 导出图片并展示
        buf = io.BytesIO()
        plt.savefig(buf, format='png', bbox_inches='tight')
        plt.close()
        buf.seek(0)
        display(Image(data=buf.getvalue()))
        return ''
    return plot_pat.sub(exec_plot_code, rendered_text)

把render_plot_block函数调用加入到render_math_doc的返回逻辑之前即可生效。

长期生效配置

如果不想每次打开Jupyter都重复运行配置,可以把上述所有代码写入IPython启动脚本:

  1. 运行ipython locate profile获取IPython配置目录
  2. 在目录下的startup文件夹中新建doc_render_config.py文件,把所有配置代码写入该文件
  3. 后续启动Jupyter/IPython时会自动加载该配置

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 21:54:03