matplotlib:在文本框中使用 LaTeX 时覆盖字符串中的下划线

matplotlib: override underscore in string when using LaTeX in text box

我需要在绘图的文本框中,在 LaTeX 环境中(因为我还需要编写一些数学代码),包含下划线的变量名称。

问题是 LaTeX 将变量名中的下划线解释为子索引命令,并且变量名被扭曲。参见(下面的 MWE):

其中变量的名称是 m_out.

如何编写包含下划线的字符串,而不让 LaTeX 将其解释为子索引命令?

在纯 LaTeX 中我可以使用 \textunderscore 命令来写:

N = m \textunderscore out \pm 0.2

正确生成:

但这在这里似乎不起作用。


MWE

import matplotlib.pyplot as plt
import matplotlib.offsetbox as offsetbox
import random

# Generate random data.
x = [random.random() for i in xrange(10)]
y = [random.random() for i in xrange(10)]

# Define string with underscore.
name = 'm_out'

# Create plot.
fig = plt.figure()
ax = plt.subplot()

# Add text box
text = r'$N={}\pm0.2$'.format(name)
ob = offsetbox.AnchoredText(text, loc=1, prop=dict(size=12))
ax.add_artist(ob)
plt.scatter(x, y)

# Save plot to file.
fig.tight_layout()
plt.savefig('out.png')

一个简单的转义就可以了:

name = 'm\_out'