PyQt 和 Matplotlib 展示 LaTeX

最近需要用 PyQt 渲染 LaTeX 公式,怎么办呢?思来想去得到了一个精妙的解决方案,分为两步:

  1. 用 Matplotlib 渲染 LaTeX 并保存成图片
  2. PyQt 显示图片

Matplotlib 渲染 LaTeX 并保存成图片

直接上函数的代码以供复制。函数将字符串 a 用 LaTeX 渲染并保存到 path 里。

import matplotlib.pyplot as plt
def renderLaTeX(a, path, usetex=True, dpi=500, fontsize=20):
    acopy = a
    plt.figure(figsize=(0.3,0.3))
    if usetex: #使用真正的 LaTeX 渲染
        try:
            a = '$\\displaystyle ' + a.strip('$') + ' $'
            plt.text(-0.3,0.9, a, fontsize=fontsize, usetex=usetex)#
        except:
            usetex = False
    
    if not usetex:
        a = acopy
        a = a.strip('$')
        a = '\n'.join([' $ '+_+' $ ' for _ in a.split('\\\\')])
        plt.text(-0.3,0.9, a, fontsize=fontsize, usetex=usetex)
        
    plt.ylim(0,1)
    plt.xlim(0,6)
    plt.axis('off') #隐藏坐标系
    plt.savefig(path, dpi=dpi, bbox_inches ='tight')
    plt.close() #释放内存

代码解释:

  • 用 plt.text 输出图片。如果参数 usetex=True 会调用真正的 LaTeX 渲染,如果 usetex=False 则使用 matplotlib 内置的方法渲染。前者的公式更加美观,但是要慢一点。

  • 这里将 plt.figure 的 figsize 设置非常小,使得在窗口里无法展示完整的公式。但是因为有 savefig 里的参数 bbox_inches = ‘tight’ ,公式被完整地保存成图片,且没有留出过大的空白!

  • 代码中对字符串 a 的处理考虑到了其换行符 (\\)。

PyQt 展示图片

以下以 PySide 6 为例。假设刚刚保存图片的路径为 ‘Formula.png’.

from PySide6 import QtCore, QtWidgets, QtGui
class MyWidget(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        self.display = QtWidgets.QLabel(self)
        self.display.setStyleSheet('border:2px groove gray')
        self.display.setAlignment(QtCore.Qt.AlignCenter)
        
        pix = QtGui.QPixmap('Formula.png').scaled(400,300,
                                QtCore.Qt.KeepAspectRatio, QtCore.Qt.SmoothTransformation)
        self.display.setGeometry(0,0,400,300)
        self.display.setPixmap(pix)

示例

执行 ( usetex 默认为 True , 即调用真正的 LaTeX)

renderLaTeX(r'c:\ |z|=1 \\ \frac{1}{2\pi i}\int_c \frac{f(z)}{z-z_0}dz = Res_{z=z_0}f(z)','Formula.png')

则 Formula.png 为:
在这里插入图片描述

  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值