省略 matplotlib 图中的连接线,例如 y = tan(x)

Ast*_*phe 7 python numpy matplotlib

我有图表y = tan(x),我想删除垂直线(见下文)。

这是我的代码:

import numpy as np
import matplotlib.pyplot as plt

# Choose evenly spaced x intervals
x = np.arange(-2*np.pi, 2*np.pi, 0.1)

# plot y = tan(x)
plt.plot(x, np.tan(x))

# Set the range of the axes
plt.axis([-2*np.pi, 2*np.pi, -2, 2])

# Include a title
plt.title('y = tan(x)')

# Optional grid-lines
plt.grid()

# Show the graph
plt.show()
Run Code Online (Sandbox Code Playgroud)

这是图表(包括不需要的垂直线):

在此处输入图片说明

我可以删除垂直线而不在 x 间隔中设置适当的间隙吗?

Sue*_*ver 8

您可以使用检查连续数据点之间的差异diff,然后确定差异为负的位置并替换这些值以NaN在绘制的线条中创建视觉中断

# Compute the tangent for each point
y = np.tan(x)

# Insert a NaN where the difference between successive points is negative
y[:-1][np.diff(y) < 0] = np.nan

# Plot the resulting discontinuous line
plt.plot(x, y)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

  • 也许`y[:-1][np.diff(y) &lt; 0] = np.nan` 更容易理解?! (2认同)
  • 更一般地说,`y[:-1][abs(np.diff(y)) &gt; n ] = np.nan` 将有助于从像 `y = sec(x)` 这样的图形中删除垂直线,其中连续点可以是正数或负数。这需要一些修补才能将 n 设置为适当的值。 (2认同)