【发布时间】:2014-09-10 14:08:46
【问题描述】:
我正在尝试将包含多个 LaTeX 命令和变量的长字符串写入图像。在保持 LaTeX 格式的同时,我无法为变量设置任意精度。
这是一个 MWE:
import matplotlib.pyplot as plt
# Define some variables names and values.
xn, yn, cod, prec, prec2 = 'r', 'p', 'abc', 2, 4
ccl = [546.35642, 6785.35416]
ect = [12.5235, 13.643241]
plt.figure()
text1 = "${}_{t} = {:.{p}f} \pm {:.{p}f} {c}$".format(xn, ccl[0], ect[0], c=cod, p=prec)
text2 = "${}_{t} = {:.{p}f} \pm {:.{p}f} {c}$".format(yn, ccl[1], ect[1], c=cod, p=prec2)
text = text1 + '\n' + text2
plt.text(0.5, 0.5, text)
plt.savefig('format_test.png', dpi=150)
这会引发错误KeyError: 't',因为它将子索引{t} 识别为变量。如果我改为使用:
text1 = "${{{a}}}_{t} = {:.{p}f} \pm {:.{p}f} {c}$".format(a=xn, ccl[0], ect[0], c=cod, p=prec)
text2 = "${{{a}}}_{t} = {:.{p}f} \pm {:.{p}f} {c}$".format(b=yn, ccl[1], ect[1], c=cod, p=prec2)
我得到SyntaxError: non-keyword arg after keyword arg,因为现在我在format 中定义了ccl[0], ect[0] 变量a=xn(第二个文本行相同)。
注意format 末尾的prec 和prec2 值,它们决定了打印时数字的小数位数。我需要传递这个变量,因为它不是固定的,我不能只设置一个固定值来替换{:.{p}f}。
如何使这些字符串行工作,同时保持 LaTeX 格式和所需的不同精度?
【问题讨论】:
标签: python matplotlib latex string-formatting