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

问题描述 投票:1回答:2

代码:

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

python discrete-mathematics
2个回答
5
投票

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


0
投票

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()
© www.soinside.com 2019 - 2024. All rights reserved.