问题
Say I made a fit and obtained the parameter a (in reality there are more). Now I want to have a little piece of text inside a plot where the parameter and its unit is stated. The idea was to use the code:
import matplotlib.pyplot as plt
a=19389.2323
plt.figure()
plt.text(0.5,0.5, r'${0:.1f}\frac{kJ}{mol}$'.format(a/1000))
However the last line causes a KeyError: 'kJ' because the curly brackets are being interpreted by the .format() instead of being interpreted as being part of the LaTeX function.
I could of course hard-code the formatted version of a into the the code, but I was hoping someone had a better solution?
回答1:
You need to escape the curly brackets for the latex commands with another pair of curly brackets.
plt.text(0.5,0.5, r'${0:.1f}\frac{{kJ}}{{mol}}$'.format(a/1000))
来源:https://stackoverflow.com/questions/42658487/interference-between-string-formatting-and-latex-functions