plotly 如何正确渲染数学公式#

安装必要依赖

pip install plotly

渲染 LaTeX 公式#

在 Plotly 中正确渲染数学公式(LaTeX 格式),关键在于 配置 MathJax 渲染环境 并遵循 Plotly 对 LaTeX 语法的支持规则。

Plotly 本身不内置 LaTeX 渲染,需借助 MathJax (一款 JavaScript 库)实现公式渲染。需完成两件事:

  1. 让 Plotly 加载 MathJax 库

  2. 用正确的 LaTeX 语法包裹公式($$ 公式 $$\( 公式 \)

在 Notebook 中,通过 IPython.display 注入 MathJax 脚本,或直接在 Plotly 布局中加载。推荐方案:

from IPython.display import display, HTML

# 注入 MathJax CDN(优先推荐)
display(HTML("<script src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/MathJax.js?config=TeX-MML-AM_CHTML'></script>"))

plotly 画出勾股定理#

Hide code cell source

import plotly.graph_objects as go
import plotly.graph_objects as go
from IPython.display import display, HTML

# 1. 注入 MathJax(必须!)
display(HTML("<script src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/MathJax.js?config=TeX-MML-AM_CHTML'></script>"))

# 创建直角三角形顶点
x = [0, 3, 0, 0]
y = [0, 0, 4, 0]

fig = go.Figure()
fig.add_trace(go.Scatter(
    x=x,
    y=y,
    mode='lines+markers',
    line=dict(color='royalblue', width=3),
    hoverinfo='none'
))

# 添加边标签和公式
annotations = [
    dict(x=1.5, y=-0.5, text=r'$a=3$', showarrow=False),
    dict(x=-0.5, y=2, text=r'$b=4$', showarrow=False),
    dict(x=1.8, y=2.2, text=r'$c=5$', showarrow=False),
    dict(x=1, y=1.5, text=r'$a^2 + b^2 = c^2$',
         font=dict(size=18), showarrow=False)
]

fig.update_layout(
    title=r'勾股定理 $\triangle ABC$',
    annotations=annotations,
    width=600,
    height=500,
    template='plotly_white'
)

# 显示并导出
# fig.show()
# fig.write_image('pythagorean_theorem.svg')  # 需要安装 kaleido pip install --upgrade kaleido
fig

渲染 Katex 公式#

KaTeX 是轻量级的数学公式渲染库,渲染速度快,适合在网页等场景中使用,我们将通过在 Plotly 的布局中注入 KaTeX 相关脚本和样式来实现公式渲染:

from IPython.display import display, HTML

# 注入 KaTeX 的 CSS 和 JS 资源,用于渲染数学公式
display(HTML("""
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.8/dist/katex.min.css" integrity="sha384-GvrOXuhMATgEsSwCs4smul74iXGOixntILdUW9XmUC6+HX0sLNAK3q71HotJqlAn" crossorigin="anonymous">
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.8/dist/katex.min.js" integrity="sha384-cpW21h6RZv/phavutF+AuVYrr+dA8xD9zs6FwLpaCct6O9ctzYFfFr4dgmgccOTx" crossorigin="anonymous"></script>
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.8/dist/contrib/auto-render.min.js" integrity="sha384-+VBxd3r6XgURycqtZ117nYw44OOcIax56Z4dCRWbxyPt0Koah1uHoK0o4+/RRE05" crossorigin="anonymous" onload="renderMathInElement(document.body);"></script>
"""))

plotly 画出饱和量化#

Hide code cell source

import plotly.graph_objects as go
import numpy as np
from IPython.display import display, HTML

# 注入 KaTeX 的 CSS 和 JS 资源,用于渲染数学公式
display(HTML("""
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.8/dist/katex.min.css" integrity="sha384-GvrOXuhMATgEsSwCs4smul74iXGOixntILdUW9XmUC6+HX0sLNAK3q71HotJqlAn" crossorigin="anonymous">
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.8/dist/katex.min.js" integrity="sha384-cpW21h6RZv/phavutF+AuVYrr+dA8xD9zs6FwLpaCct6O9ctzYFfFr4dgmgccOTx" crossorigin="anonymous"></script>
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.8/dist/contrib/auto-render.min.js" integrity="sha384-+VBxd3r6XgURycqtZ117nYw44OOcIax56Z4dCRWbxyPt0Koah1uHoK0o4+/RRE05" crossorigin="anonymous" onload="renderMathInElement(document.body);"></script>
"""))

# 1. 准备数据
# 上方数轴坐标
upper_line_x = np.linspace(-1.2, 1.2, 100)
upper_line_y = np.full_like(upper_line_x, 0.5)

# 下方数轴坐标
lower_line_x = np.linspace(-1.2, 1.2, 100)
lower_line_y = np.full_like(lower_line_x, -0.5)

# 上方数据点(示例)
upper_points_x = [-1, -0.7, -0.6, 0, 0.6, 0.7, 0.8, 1]
upper_points_y = [0.5] * len(upper_points_x)

# 下方数据点(示例,对应映射后位置)
lower_points_x = [-0.8, -0.5, -0.4, 0, 0.4, 0.5, 0.6, 0.8]
lower_points_y = [-0.5] * len(lower_points_x)

# 2. 创建 Plotly 图形对象
fig = go.Figure()

# 3. 添加上下绿色数轴
fig.add_trace(go.Scatter(
    x=upper_line_x, y=upper_line_y,
    mode='lines',
    line=dict(color='green', width=2),
    name='Upper Line'
))

fig.add_trace(go.Scatter(
    x=lower_line_x, y=lower_line_y,
    mode='lines',
    line=dict(color='green', width=2),
    name='Lower Line'
))

# 4. 添加橙色“×”标记
fig.add_trace(go.Scatter(
    x=upper_points_x, y=upper_points_y,
    mode='markers',
    marker=dict(color='orange', symbol='x', size=15, line=dict(width=2)),
    name='Upper Points'
))

fig.add_trace(go.Scatter(
    x=lower_points_x, y=lower_points_y,
    mode='markers',
    marker=dict(color='orange', symbol='x', size=15, line=dict(width=2)),
    name='Lower Points'
))

# 5. 添加虚线映射关系
for u_x, l_x in zip(upper_points_x, lower_points_x):
    fig.add_trace(go.Scatter(
        x=[u_x, l_x], y=[0.5, -0.5],
        mode='lines',
        line=dict(color='black', dash='dash', width=1),
        showlegend=False  # 不显示在图例
    ))

# 6. 添加 KaTeX 公式标注
fig.add_annotation(
    x=0, y=0.8,
    text=r'$$\text{饱和量化:}\quad Q = \text{clip}\left( \frac{R}{\text{scale}}, -127, 127 \right)$$',
    showarrow=False,
    font=dict(size=14, color='black')
)

# 7. 添加文本标注(使用 KaTeX 语法,用 $ 包裹公式)
# 上方刻度,KaTeX 用 $ 包裹公式
fig.add_annotation(
    x=-1.2, y=0.65,
    text=r'$-|\max|$',
    showarrow=False,
    font=dict(size=12)
)
fig.add_annotation(
    x=0, y=0.65,
    text=r'$0.0$',
    showarrow=False,
    font=dict(size=12)
)
fig.add_annotation(
    x=1.2, y=0.65,
    text=r'$+|\max|$',
    showarrow=False,
    font=dict(size=12)
)

# 下方刻度
fig.add_annotation(
    x=-0.8, y=-0.65,
    text=r'$-127$',
    showarrow=False,
    font=dict(size=12)
)
fig.add_annotation(
    x=0, y=-0.65,
    text=r'$0$',
    showarrow=False,
    font=dict(size=12)
)
fig.add_annotation(
    x=0.8, y=-0.65,
    text=r'$127$',
    showarrow=False,
    font=dict(size=12)
)

# 右下角标识
fig.add_annotation(
    x=1.0, y=-0.8,
    text='xinetzone',
    showarrow=False,
    font=dict(size=12, color='gray'),
    align='right'
)

# 8. 布局设置(隐藏坐标轴、调整边距等)
fig.update_layout(
    xaxis=dict(showticklabels=False, showgrid=False, zeroline=False),
    yaxis=dict(showticklabels=False, showgrid=False, zeroline=False),
    margin=dict(l=20, r=20, t=20, b=20), # 给公式预留空间
    hovermode='closest',
    showlegend=False,  # 隐藏图例(如需显示可设为 True)
    paper_bgcolor='white',
    plot_bgcolor='white',
)

# 9. 显示图形
fig.show()

代码说明

  1. 注入 KaTeX 资源:通过 display(HTML(...)) 注入 KaTeX 的 CSS 样式文件和 JS 脚本文件,其中 auto-render.min.js 用于自动渲染页面中的数学公式,它会在页面加载完成后查找包含在 $...$$$...$$ 中的内容并进行渲染。

  2. 公式编写:在 add_annotationtext 参数中,使用 KaTeX 支持的语法,用 $ 包裹数学公式部分(如 r'$-|\max|$' ),KaTeX 会自动识别并渲染成美观的数学符号。

  3. 其他绘图逻辑:和之前 Plotly 绘图的逻辑一致,包括绘制数轴、数据点、虚线连接以及设置布局等,确保图形的结构和样式符合需求。

这样,运行代码后,在支持的环境(如 Jupyter Notebook 等)中,就可以利用 KaTeX 来正确渲染数学公式,呈现出包含饱和量化映射关系和相应标注的示意图 。如果是在纯 Python 脚本运行且希望在浏览器中查看效果,代码逻辑也是类似的,同样能借助 KaTeX 实现公式渲染。

饱和量化是数字信号处理中的关键技术,主要用于:

Q(x)={qmaxxTmaxqminxTminround(xΔ)×Δ其他 \begin{split}Q(x) = \begin{cases} q_{\text{max}} & x \geq T_{\text{max}} \\q_{\text{min}} & x \leq T_{\text{min}} \\\text{round}(\frac{x}{\Delta}) \times \Delta & \text{其他}\end{cases}\end{split}

核心特征

  1. 阈值限定(Tmax/Tmin

  2. 量化区间保护(防止溢出)

  3. 非线性映射

典型应用

  • 神经网络权重量化(防止梯度爆炸)

  • ADC模数转换(电压范围保护)

  • 图像传感器(光电信号规整)

对比普通量化

特征

饱和量化

普通量化

溢出处理

钳位保护

模运算循环

误差分布

边界集中

均匀分布

硬件实现

比较器+计数器

移位寄存器