简体   繁体   English

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

[英]matplotlib: override underscore in string when using LaTeX in text box

I need to write in the text box of a plot, and within a LaTeX environment (since I also need to write some math code), the name of a variable that contains an underscore. 我需要在绘图的文本框中以及在LaTeX环境中(因为我还需要编写一些数学代码)编写包含下划线的变量的名称。

The problem is that LaTeX interprets the underscore in the variable's name as a subindex command, and the name of the variable is distorted. 问题在于,LaTeX将变量名称中的下划线解释为子索引命令,并且变量名称失真。 See (MWE below): 请参阅(下面的MWE):

在此处输入图片说明

where the name of the variable is m_out . 变量名称为m_out

How can I write a string containing an underscore without LaTeX interpreting it as the subindex command? 如何在不将LaTeX解释为subindex命令的情况下编写包含下划线的字符串?

In pure LaTeX I could use the \\textunderscore command to write: 在纯LaTeX中,我可以使用\\textunderscore命令来编写:

N = m \textunderscore out \pm 0.2

which correctly produces: 正确产生:

在此处输入图片说明

but this doesn't seem to work here. 但这似乎在这里不起作用。


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

A simple escape does the trick: 一个简单的转义就能达到目的:

name = 'm\_out'

matplotlib生成的图像

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM