使用 python 库 matplotlib,我找到了解决这个问题的建议:
Displaying (nicely) an algebraic expression in PyQt通过使用 matplotlibs TeX markup .
我想做的是从我的 python 程序中获取表示数学表达式的 TeX 代码,并将其保存为可以在我的 PyQt GUI 中显示的图像,而不是以难看的纯文本显示方程。
本质上是这样的……
import matplotlib.pyplot as plt
formula = '$x=3^2$'
fig = plt.figure()
fig.text(0,0,formula)
fig.savefig('formula.png')
但是,pyplot 模块主要用于显示图形和绘图,而不是我需要的文本示例。该代码的结果通常是巨大的白色空白图像左下角的一小段文本。
如果我的公式涉及分数,因此需要向下空间,它会被截断,如下图所示。
请注意,这是一张空白图片;看向显示屏的左侧
Fraction at coordinate (0,0) truncated and surrounded by whitespace
我相信我可以创建一个非常大的(空间方面的)图形,在空白图的中间写下公式,保存它,然后使用像素分析将它裁剪成尽可能小的图像,但这似乎相当原油。
绘图是 matplotlib 的唯一预期输出吗?
有没有专门用于输出方程式的东西,不需要我担心文本的所有额外空间或位置?
谢谢!
请您参考如下方法:
诀窍是渲染文本,然后获取其边界框,最后调整图形大小和文本在新图形中的垂直位置。这样保存了两次图形,但是在任何文本引擎中都很常见,只有在文本渲染后才能正确获取正确的边界框和其他参数。
import pylab
formula = r'$x=3^2, y = \frac{1}{\frac{2}{3}}, %s$' % ('test' * 20)
fig = pylab.figure()
text = fig.text(0, 0, formula)
# Saving the figure will render the text.
dpi = 300
fig.savefig('formula.png', dpi=dpi)
# Now we can work with text's bounding box.
bbox = text.get_window_extent()
width, height = bbox.size / float(dpi) + 0.005
# Adjust the figure size so it can hold the entire text.
fig.set_size_inches((width, height))
# Adjust text's vertical position.
dy = (bbox.ymin/float(dpi))/height
text.set_position((0, -dy))
# Save the adjusted text.
fig.savefig('formula.png', dpi=dpi)
0.005 常量被添加到 width 和 height 中,因为很明显,对于某些文本,Matplotlib 返回了一个略微低估的边界框,即, 小于要求。
