我有以下代码来在我的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 的 {
花括号}
冲突?