简体   繁体   中英

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 在此处输入图片说明

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.

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)

在此处输入图片说明

Alternatively, simply escape the character so it's not interpreted as a tab.

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)

NB: Show the legend/label as well

plt.legend()

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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