Interference between string formatting and LaTeX functions

南楼画角 提交于 2019-12-12 03:49:41

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!