Matplotlib 运行时错误 Latex 无法处理以下字符串

use*_*933 5 python plot latex matplotlib

我试图向图例添加一些文本和乳胶,但遇到了一些错误。我在文档中看到了多个这样的示例,但似乎无法弄清楚我做错了什么。

我在下面做错了什么labels?我在图下方添加了看起来最好的示例和理想标签的示例。

import matplotlib.pyplot as plt
plt.rc('text', usetex=True)

x_values = [1,2,3,4]
y_values = [1,2,3,4]

# example that kind of works
plt.plot(x_values,y_values, 
label = r'$|askprice_a - askprice_b| >$ threshold')

plt.legend(loc=0)
plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

# better example
plt.plot(x_values,y_values, 
label = r' $|\text{bid_price}_{a} - \text{bid_price}_{b}| > \text{threshold}$')

plt.legend(loc=0)
plt.show()
Run Code Online (Sandbox Code Playgroud)
RuntimeError: latex was not able to process the following string:
b' $|\\\\text{bid_price}_{a} - \\\\text{bid_price}_{b}| > \\\\text{threshold}$'
Run Code Online (Sandbox Code Playgroud)

reh*_*qds 0

仅在需要数学符号的地方放置 $ 符号即可,例如:

plt.plot(x_values, y_values, label = 
         r'$|$bid price$_a$ - \textit{bid price$_b |$} $>$ \textbf{threshold}')
Run Code Online (Sandbox Code Playgroud)

并使用

plt.rcParams['text.usetex'] = True
Run Code Online (Sandbox Code Playgroud)

代替

plt.rc('text', usetex=True)
Run Code Online (Sandbox Code Playgroud)