Matplotlib runtime error latex was not able to process the following string

Viewed 114

I am trying to add some text and latex to a legend and ran into some errors. I have seen multiple examples of this here in the documentation but can't seem to figure out what I am doing wrong.

What am I doing wrong in my labels below? I have added my example that looks best and the example of my ideal label below the plot.

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()

enter image description here

# 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()
RuntimeError: latex was not able to process the following string:
b' $|\\\\text{bid_price}_{a} - \\\\text{bid_price}_{b}| > \\\\text{threshold}$'
1 Answers

Putting the $ sign only where math notation is needed would work, for example:

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

And use

plt.rcParams['text.usetex'] = True

instead of

plt.rc('text', usetex=True)
Related