【问题标题】:How to render Latex markup using Python?如何使用 Python 渲染 Latex 标记?
【发布时间】:2011-05-01 00:09:30
【问题描述】:

如何在 python 中显示一个简单的乳胶公式? 也许 numpy 是正确的选择?

编辑:

我有类似的python代码:

a = '\frac{a}{b}'

并希望将其打印在图形输出中(如 matplotlib)。

【问题讨论】:

  • “在 python 中显示乳胶公式”是什么意思。您想从 .tex 文件中提取公式并将其打印到 python 的标准输出,在 python 中实现 .tex (pdf/ps) 文件中显示的公式还是什么?
  • 你能澄清一下吗?你想在哪里打印?你想生成图像还是在 gui 中寻找东西?
  • 很抱歉这个不清楚的问题。 :/ 请查看编辑。
  • 查看 matplotlib 站点上的文档:-Text rendering With LaTeX

标签: python latex formula


【解决方案1】:

正如 Andrew 所建议的,使用 matplotlib 的工作很少。

import matplotlib.pyplot as plt
a = '\\frac{a}{b}'  #notice escaped slash
plt.plot()
plt.text(0.5, 0.5,'$%s$'%a)
plt.show()

【讨论】:

  • 有人可以向我解释第 3 行吗?分号只是一个错字吗?
  • @Annan 分号只是分隔两行。您也可以将plt.text(0.5,0.5,'$%s$'%a) 换行。
【解决方案2】:

基于 this one 特定于 Jupyter 笔记本的答案,使用 f-string 格式化 $x_i$ 变量:

from IPython.display import display, Latex
for i in range(3):
    display(Latex(f'$x_{i}$'))

注意:f-string(格式化字符串文字)使用花括号插入 Python 变量 i 的值。您需要 double the curly braces (f'{{}}') 才能在 LaTeX 代码中实际使用 {}。否则,您可以直接在普通 Python 字符串(不是 f 字符串)中使用单个花括号。

旁注:我很惊讶 Stack Overflow 仍然doesn’t have a math markup

【讨论】:

  • 在我看来,这应该是答案。简洁明了
【解决方案3】:

在 Pandas 中创建数学公式。

a = r'\frac{a}{b}'
ax = plt.axes([0,0,0.3,0.3]) #left,bottom,width,height
ax.set_xticks([])
ax.set_yticks([])
ax.axis('off')
plt.text(0.4,0.4,'$%s$' %a,size=50,color="green")

a = r'f(x) = \frac{\exp(-x^2/2)}{\sqrt{2*\pi}}'
ax = plt.axes([0,0,0.3,0.3]) #left,bottom,width,height
ax.set_xticks([])
ax.set_yticks([])
ax.axis('off')
plt.text(0.4,0.4,'$%s$' %a,size=50,color="green")

【讨论】:

    【解决方案4】:

    通过在~/.matplotlib/matplotlibrc 中设置text.usetex: True,Matplotlib 已经可以进行 TeX。然后,您可以在所有显示的字符串中使用 TeX,例如,

    ylabel(r"Temperature (K) [fixed $\beta=2$]")
    

    (请务必使用$,就像在正常的内联 TeX 中一样!)。字符串前的r 表示不进行替换;否则你必须像提到的那样避开斜线。

    更多信息请访问matplotlib 网站。

    【讨论】:

    • matplotlibrc 是否在 matplotlib 文件夹中?我找不到它:/
    • 在 UNIX 系统上,它位于我上面提到的目录中。在windows上,我不知道。检查文档。
    • 我使用的是 Ubuntu 12 并在系统(不是用户)中安装了 matplotlib,在我的情况下它在 /etc/matplotlibrc
    • 这个选项真的有必要吗? The documentation 表示如果您想使用实际的 LaTeX 安装来获得高级功能,而 TeX 数学渲染是 natively supported
    【解决方案5】:

    没有刻度:

    a = r'\frac{a}{b}'
    ax = plt.axes([0,0,0.1,0.2]) #left,bottom,width,height
    ax.set_xticks([])
    ax.set_yticks([])
    plt.text(0.3,0.4,'$%s$' %a,size=40)
    

    【讨论】:

      【解决方案6】:

      用 matplotlib 绘图,

      import matplotlib.pyplot as plt
      a = r'\frac{a}{b}'
      ax=plt.subplot(111)
      ax.text(0.5,0.5,r"$%s$" %(a),fontsize=30,color="green")
      plt.show()
      

      【讨论】:

        猜你喜欢
        • 2016-11-05
        • 1970-01-01
        • 2015-12-18
        • 2018-05-26
        • 2016-06-20
        • 2018-07-13
        • 2013-11-18
        • 1970-01-01
        相关资源
        最近更新 更多