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

时间:2019-02-03 18:02:41

标签: python discrete-mathematics

代码:

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

预期结果:

enter image description here

我得到的结果:

enter image description here

2 个答案:

答案 0 :(得分:2)

我认为有两个问题。第一个关于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)

您应该看到以下内容: enter image description here

答案 1 :(得分:1)

bnaecker对.linspace的建议以及Omit joining lines in matplotlib plot e.g. y = tan(x)的回复有助于产生以下方法:

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$', '$3\pi/2$', '$2\pi$']

plt.xticks(radians, radian_labels)

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