Gab*_*iel 6 python latex matplotlib string-formatting
我正在尝试将一些带有几个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)
Run Code Online (Sandbox Code Playgroud)
这会引发错误,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)
Run Code Online (Sandbox Code Playgroud)
我得到的SyntaxError: non-keyword arg after keyword arg,因为现在我有ccl[0], ect[0]变量format之后定义a=xn(同为第二个文本行).
请注意,其末尾的值prec和prec2值format决定了打印时数字的小数位数.我需要传递这个变量,因为它没有修复,我不能只设置一个固定值来替换{:.{p}f}.
如何在保持LaTeX格式和所需的不同精度的同时使这些字符串行有效?
我认为你需要一个额外的大括号t.这对我有用:
text1 = r"${}_{{t}} = {:.{p}f} \pm {:.{p}f} {c}$".format(xn, ccl[0], ect[0], c=cod, p=prec)
text2 = r"${}_{{t}} = {:.{p}f} \pm {:.{p}f} {c}$".format(yn, ccl[1], ect[1], c=cod, p=prec2)
Run Code Online (Sandbox Code Playgroud)
添加双花括号意味着它们按字面意思处理,而不是作为python格式语法的一部分

| 归档时间: |
|
| 查看次数: |
2626 次 |
| 最近记录: |