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

2024-05-21 03:33:41 发布

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

我有图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()

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

enter image description here

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


Tags: the代码importnumpyplottitlematplotlibas
3条回答

我们可以使用切线的定义来过滤掉x的余弦与0非常接近的点。在

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 4*np.pi, 666)
y = np.tan(x)

y[np.abs(np.cos(x)) <= np.abs(np.sin(x[1]-x[0]))] = np.nan

plt.plot(x, y)
plt.ylim(-3,3)

plt.show()

这仅适用于等间距数据。在

您可以使用^{}检查连续数据点之间的差异,然后确定差异在哪里为负,并用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)

enter image description here

如果您愿意承担更强大的数学程序的开销,SageMath可以帮助您:

plot(tan(x),(x,-2*pi,2*pi),detect_poles=True,ymin=-2,ymax=2,ticks=[pi/2,None],tick_formatter=pi)

enter image description here

(原点处的小开口是我以前从未见过的,希望很快会再次修复。)

相关问题 更多 >