matplotlib中的TeX渲染,花括号和字符串格式化语法

时间:2011-05-20 07:08:57

标签: python string matplotlib tex

我有以下几行在我的matplotlib图中呈现TeX注释:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc

rc('text', usetex=True)
rc('font', family='serif')

voltage = 220

notes = r"\noindent $V_2 = {0:.5} V$".format(voltage)

plt.annotate(notes, xy=(5,5), xytext=(7,7))
plt.show()

它完美无缺,但我的第一个挑剔是V是一个度量单位,因此它应该是文本模式,而不是(斜体)数学模式。我尝试以下字符串:

notes = r"\noindent $V_2 = {0:.5} \text{V}$".format(voltage)

这会引发错误,因为{花括号}是Python的字符串格式化语法的所有权。在上面一行中,只有{0:.5}是正确的; {V}被视为陌生人。例如:

s1 = "Hello"
s2 = "World!"
print "Some string {0} {1}".format(s1, s2)

应该提供Some string Hello World!

如何确保TeX的{花括号}不会干扰Python的{花括号}

2 个答案:

答案 0 :(得分:20)

你需要加倍支撑才能按字面意思对待:

r"\noindent $V_2 = {0:.5} \text{{V}}$".format(voltage)
顺便说一句,你也可以写

\text V

但最好的是

\mathrm V

因为单位不是真正的文字符号。

答案 1 :(得分:6)

你对它们进行双重支撑:

>>> print '{{asd}} {0}'.format('foo')
{asd} foo
相关问题