Search code examples
pythonmatplotliblatexlegendaxis-labels

Latex script in matplotlib


I wish to use latex script $\theta$ for labelling the axes and legends in matplotlib figure. So I use the following piece of code.

y = np.linspace(0, 2*np.pi, 200)
plt.plot(y, np.sin(y)*np.cos(y), lw=3, label='$sin(\theta) cos(\theta)$')

plt.xlabel('$\theta$', fontsize=40)
plt.ylabel('$P(\theta,t)$', fontsize=40)

But this does not work and returns the following figure enter image description here

The code works for $\Theta$, but I don't want to change the variable name. The same problem occurs with $\rho$, $\tau$, $\alpha$, $\beta$. Please give some tips on how to get out of this problem.

Thanks for your help.


Solution

  • Use raw strings, otherwise the \t in your strings will be interpreted as TAB.

    Both string and bytes literals may optionally be prefixed with a letter 'r' or 'R'; such strings are called raw strings and treat backslashes as literal characters.

    You should generally do that for strings containing Latex expressions, as they very often contain backslashes.

    y = np.linspace(0, 2*np.pi, 200)
    plt.plot(y, np.sin(y)*np.cos(y), lw=3, label=r'$sin(\theta) cos(\theta)$')
    
    plt.xlabel(r'$\theta$', fontsize=40)
    plt.ylabel(r'$P(\theta,t)$', fontsize=40)
    

    enter image description here