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

如何在matplotlib MathText中插入变量值并生成代值后的计算结果公式?

实现方案

你可以通过字符串模板占位+变量字典+SymPy自动计算的方案同时满足两个需求,具体实现如下:

前置依赖

需要先安装SymPy用于自动解析公式和计算结果:
pip install sympy

完整实现代码

import matplotlib.pylab as plt
from sympy import symbols, latex, sympify

def make_equation(code,fsize=20,imgheight=70):
    fig=plt.figure(figsize=(7, 0.1))
    plt.annotate(code,
               xy=(.4, 0.1), ha='center', fontsize=fsize)
    plt.axis('off')

def generate_calc_docs(formula_template: str, var_dict: dict, fsize=20):
    """
    批量生成计算过程所需的全部内容
    :param formula_template: 通用公式的LaTeX模板,变量用{变量名}作为占位符,LaTeX原生大括号需双写转义
    :param var_dict: 变量取值字典,key为变量名,value为实际取值
    :param fsize: 公式字体大小
    :return: 通用公式、代值后公式、最终计算结果
    """
    # 1. 生成原始通用公式
    var_placeholder = {k: k for k in var_dict.keys()}
    general_formula = r"$" + formula_template.format(**var_placeholder) + r"$"
    # 2. 生成代入实际取值后的公式
    substituted_formula = r"$" + formula_template.format(**var_dict) + r"$"
    # 3. 自动计算最终结果,生成带结果的完整公式
    expr = sympify(formula_template.format(**var_dict))
    calc_result = expr.evalf()
    result_formula = r"$" + f"{calc_result} = " + formula_template.format(**var_dict) + r"$"

    # 生成对应的mathtext元素,可直接对接Reportlab流式输出
    make_equation(general_formula, fsize)
    make_equation(substituted_formula, fsize)
    make_equation(result_formula, fsize)

    return general_formula, substituted_formula, calc_result

# 调用示例
if __name__ == "__main__":
    # 示例1:你提供的分式计算示例
    formula_tpl = r"(\frac{5 - \frac{1}{{x}}}{4})"
    var_dict = {"x": 2}
    general, substituted, res = generate_calc_docs(formula_tpl, var_dict)
    print("原始公式:", general)
    print("代值后公式:", substituted)
    print("计算结果:", res)

    # 示例2:你描述的A+B计算示例
    formula_tpl2 = r"A + B"
    var_dict2 = {"A":1, "B":2}
    general2, substituted2, res2 = generate_calc_docs(formula_tpl2, var_dict2)

问题对应说明

  • 关于mathtext插入变量值:通过Python字符串格式化的占位符能力实现,提前在LaTeX模板中把变量位置用{变量名}预留,直接通过字典的format方法批量替换即可,注意LaTeX原生的大括号需要双写转义,避免被识别为Python占位符。
  • 关于批量生成三类内容:上述方案已经通过变量字典实现了通用公式、代值公式、计算结果的同步生成,不需要手动计算,复杂公式也可以通过SymPy的解析能力自动求解,避免人工计算错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 17:36:02