在Matplotlib中用LaTeX标记刻度

16
在matplotlib的绘图中,我特别想在x轴上用LaTeX标记点,如pi/2、pi、3pi/2等。我该怎么做?
2个回答

28

使用 plt.xticks 命令可以放置 LaTeX 刻度线。更多详情请参见此文档页面

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


2
如果您正在对轴句柄执行此操作,则需要进行两个单独的调用:一个是 set_xticks,另一个是 set_xticklabels。例如,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$']) - Aaron Voelker
1
@AaronVoelker:另一种方法是 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$']) - unutbu
我猜大多数人在尝试在matplotlib中使用TeX时失败,是因为他们忘记在TeX中添加 $,或者忘记转义反斜杠(或使用原始字符串字面量r'')。 - RubenLaguna

1
另一种可能性是更新pyplot rcParams,虽然这可能更像是一种黑客方式而不是合法的方法。
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()

输出


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接