在轴坐标上使用自定义记号

2024-04-26 06:21:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在matplotlib中绘制一些函数。但是我想改变通常的x和y坐标。例如,我在[-pi, pi]中绘制y=sin(x)。但是x轴以这种方式显示1, 2, 3,...,而我想要x:-pi, 0, pi,...这可能吗?你知道吗

我的代码

import matplotlib as mpl
mpl.rc('text', usetex = True)
mpl.rc('font', family = 'serif')
import matplotlib.pyplot as plt
import numpy as np

plt.gca().set_aspect('equal', adjustable='box')
plt.style.use(['ggplot','dark_background'])

x = np.arange(-np.pi,np.pi,0.001)
y = np.sin(x)

plt.xlabel('$x$')
plt.ylabel('$y$')
plt.plot(x,y, label='$y=\sin x$')
plt.legend()
plt.show()

输出enter image description here

如何更改坐标轴上的标记?非常感谢。你知道吗


Tags: 函数代码textimportmatplotlibasnp方式
2条回答

在这里,您可以显示任意范围的pi。只需在plt.plot之后向代码中添加以下行

xlabs = [r'%d$\pi$'%i if i!=0 else 0 for i in range(-2, 3, 1)]
xpos = np.linspace(-2*np.pi, 2*np.pi, 5)
plt.xticks(xpos, xlabs)

输出enter image description here

是的,您可以在轴上设置自定义记号,并将它们等距设置;为此,您需要将记号与关联的值一起设置为序列:

import matplotlib as mpl
mpl.rc('text', usetex = True)
mpl.rc('font', family = 'serif')
import matplotlib.pyplot as plt
import numpy as np


plt.gca().set_aspect('equal', adjustable='box')
plt.style.use(['ggplot','dark_background'])

x = np.arange(-np.pi,np.pi,0.001)
y = np.sin(x)

# the following two sequences contain the values and their assigned tick markers
xx = [-np.pi + idx*np.pi/4 for idx in range(10)]
xx_t = ['$-\\pi$', '$\\frac{-3\\pi}{4}$', '$\\frac{-\\pi}{2}$', '$\\frac{-\\pi}{4}$', '0', 
        '$\\frac{\\pi}{4}$', '$\\frac{\\pi}{2}$', '$\\frac{3\\pi}{4}$', '$\\pi$']
plt.xticks(xx, xx_t)   # <  the mapping happens here

plt.xlabel('$x$')
plt.ylabel('$y$')
plt.plot(x,y, label='$y=\sin x$')
plt.legend()
plt.show()

enter image description here

相关问题 更多 >