matplotlib - Python combining the format method with long strings that use LaTeX -
i'm trying write long string several latex commands , variables image. i'm having trouble setting arbitrary precision variables while maintaining latex formatting.
here's mwe:
import matplotlib.pyplot plt # define variables names , 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)
this throws error keyerror: 't'
since recognizing sub-index {t}
variable. if instead use:
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)
i syntaxerror: non-keyword arg after keyword arg
since have ccl[0], ect[0]
variables in format
defined after a=xn
(same second text line).
notice prec
, prec2
values @ end of format
determines number of decimal places number have when printed. need pass variable because not fixed, can't set fixed value replace {:.{p}f}
.
how can make these string lines work while keeping latex formatting , different precision needed?
i think need curly brace around t
. works me:
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)
adding double curly brace means treated literally, not part of python format syntax
Comments
Post a Comment