Use TeX expression "\tanh" in matplotlib legend

Viewed 54

I'm having some trouble using the TeX "\tanh" expression in my matplotlib chart legend. The reason is that "\t" is also the reserved symbol in Python used for tabs. Hence my expression doesn't show properly. How can I make this work?

This is my code

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-10, 10, 1000)
y1 = np.e ** x / (np.e ** x + 1)
y2 = (np.e ** (2 * x) - 1) / (np.e ** (2 * x) + 1)

plt.figure(figsize=(6, 6 / 16 * 9))
ax = plt.gca()
ax.plot(x, y1, color=(0, 101/255, 189/255), linewidth=2, label='$\sigma(x)$')
ax.plot(x, y2, color=(227/255, 114/255, 34/255), linewidth=2, label='$\tanh(x)$')

ax.set_ylim(-1, 1)
ax.set_xlim(-6, 6)
ax.grid(True, which='both', ls='-')
plt.legend()

plt.show()

This is the (wrong) outcome

Activation functions

1 Answers

I believe you need to use a raw-string to ignore the \t, so label=r'$\tanh(x)$'.

enter image description here

Related