Mark ticks in latex in matplotlib
Asked Answered
R

2

16

In a plot in matplotlib I specially want to mark points on the x-axis as pi/2, pi, 3pi/2 and so on in latex. How can I do it?

Rudie answered 16/10, 2012 at 18:7 Comment(0)
M
28

The plt.xticks command can be used to place LaTeX tick marks. See this doc page for more details.

import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np

cos = np.cos
pi = np.pi

# This is not necessary if `text.usetex : True` is already set in `matplotlibrc`.    
mpl.rc('text', usetex = True)
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
t = np.linspace(0.0, 2*pi, 100)
s = cos(t)
plt.plot(t, s)

plt.xticks([0, pi/2, pi, 3*pi/2, 2*pi],
           ['$0$', r'$\frac{\pi}{2}$', r'$\pi$', r'$\frac{3\pi}{2}$', r'$2\pi$'])
plt.show()

enter image description here

Morbihan answered 16/10, 2012 at 18:33 Comment(3)
If you're doing this to an axis handle, then you need two separate calls: one to set_xticks and another to set_xticklabels. For example, ax.set_xticks([0, pi/2, pi, 3*pi/2, 2*pi]) followed by ax.set_xticklabels(['$0$', r'$\frac{\pi}{2}$', r'$\pi$', r'$\frac{3\pi}{2}$', r'$2\pi$']).Estipulate
@AaronVoelker: Another way to do it is ax.set(xticks=[0, pi/2, pi, 3*pi/2, 2*pi], xticklabels=['$0$', r'$\frac{\pi}{2}$', r'$\pi$', r'$\frac{3\pi}{2}$', r'$2\pi$']).Morbihan
I guess most of the time people that try to use TeX in matplotlib fail because they forget to wrap the TeX in $ or because they forget to escape the backslashes (or use raw string literall r'')Champerty
R
1

Another possibility is to update the pyplot rcParams, although this might be rather a hack than a legitimate way.

import matplotlib.pyplot as plt
import numpy as np

cos = np.cos
pi  = np.pi

params = {'mathtext.default': 'regular' }  # Allows tex-style title & labels
plt.rcParams.update(params)

fig = plt.figure()
ax  = fig.add_subplot(1, 1, 1)
t   = np.linspace(0.0, 2*pi, 100)
s   = cos(t)
plt.plot(t, s)

ax.set_xticks([0, pi/2, pi, 3*pi/2, 2*pi])
ax.set_xticklabels(['$0$', r'$\frac{\pi}{2}$', r'$\pi$', r'$\frac{3\pi}{2}$', r'$2\pi$'])
plt.show()

Output

Rail answered 30/7, 2020 at 14:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.