字符串格式和 LaTeX 函数之间的干扰 [英] Interference between string formatting and LaTeX functions

查看:35
本文介绍了字符串格式和 LaTeX 函数之间的干扰的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我适合了,并获得了参数 a (实际上还有更多).现在,我想在标有参数及其单位的绘图中保留一小段文字.这个想法是使用代码:

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)) 

但是最后一行会导致 KeyError:'kJ',因为大括号是由 .format()解释的,而不是被解释为LaTeX功能.

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.

我当然可以将 a 的格式化版本硬编码到代码中,但是我希望有人能有更好的解决方案?

I could of course hard-code the formatted version of a into the the code, but I was hoping someone had a better solution?

推荐答案

您需要使用另一对大括号对乳胶命令的大括号进行转义.

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)) 

这篇关于字符串格式和 LaTeX 函数之间的干扰的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆