如何用 pyplot 和 numpy 绘制 tan(x)

How to plot tan(x) with pyplot and numpy

代码:

import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10000)
plt.plot(x, np.tan(x))
plt.show()

预期结果:

我得到的结果:

我认为有两个问题。第一个是关于np.linspace,第二个是关于密谋。

np.linspace默认返回给定范围内的50个元素。因此,您在 (0, 10000) 上绘制了 50 个点,这意味着元素的间距非常大。此外,该范围对于正切函数没有多大意义。我会使用更小的东西,可能是 +/- 2 * pi。

第二个问题是y轴。正切函数在 pi/2 的倍数处很快发散到无穷大,这意味着您通过绘制完整的 y 范围错过了很多有趣的行为。下面的代码应该可以解决这些问题。

x = np.linspace(-2 * np.pi, 2 * np.pi, 1000)
plt.plot(x, np.tan(x))
plt.ylim(-5, 5)

您应该会看到如下内容:

bnaecker 关于 .linspace 的建议和 的回复帮助产生了以下方法:

import matplotlib.pyplot as plt
import numpy as np

# .linspace arguments are (start, end, number_of_steps)
x = np.linspace(-2 * np.pi, 2 * np.pi, 1000)
y = np.tan(x)

# This operation inserts a NaN where the difference between successive points is negative
# NaN means "Not a Number" and NaNs are not plotted or connected
# I found this by doing a search for "How to plot tan(x) in matplotlib without the connecting lines between asymtotes"
y[:-1][np.diff(y) < 0] = np.nan

# show grid
plt.grid()

plt.xlabel("x")
plt.ylabel("$tan(x)$")

# Set the x and y axis cutoffs
plt.ylim(-10,10)
plt.xlim(-2 * np.pi, 2 * np.pi)

# x_labels in radians
# For a more programmatic approach to radians, see https://matplotlib.org/3.1.1/gallery/units/radian_demo.html
radian_multiples = [-2, -3/2, -1, -1/2, 0, 1/2, 1, 3/2, 2]
radians = [n * np.pi for n in radian_multiples]
radian_labels = ['$-2\pi$', '$-3\pi/2$', '$\pi$', '$-\pi/2$', '0', '$\pi/2$', '$\pi$', '\pi/2$', '\pi$']

plt.xticks(radians, radian_labels)

plt.title("$y = tan(x)$", fontsize=14)
plt.plot(x, y)
plt.show()

我在搜索时发现的类似解决方案可能对其他人有帮助

t = np.arange(0.0, 1, 0.01)
s = np.tan(t)
fig, ax = plt.subplots()
ax.plot(t, s)
ax.set(xlabel='radians', ylabel='tan(x)',
       title='Tangent Plot')
ax.grid()
plt.show()

https://www.includehelp.com/python/plotting-trigonometric-functions.aspx

有关详细信息,请参阅上文 link