2017-03-16 124 views
2

我有图y = tan(x),我想删除垂直线(见下文)。忽略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() 

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

enter image description here

我可以删除垂直线而没有设置适当的间隙进入X间隔?

回答

2

您可以检查时COS = 0,所以写了条件语句,如垂直渐近线会发生使用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) 

enter image description here

+2

也许'y [: - 1] [np.diff(y)<0] = np.nan'更容易理解?! – ImportanceOfBeingErnest

+0

@ImportanceOfBeingErnest是更清晰一点,可能更高性能。谢谢! – Suever

+0

我不知道你可以输入值为NaN来制作不连续的曲线。 – Astrophe

1

使用tan,sin/cos的定义。 如果COS(x)= 0:! plt.plot(X,np.tan(X))

+3

这不会开箱即用。即使'cos(np.pi/2。)'在数字上也不等于'0'。 – ImportanceOfBeingErnest

2

人们可以使用的切线的定义过滤出那些poi nts其中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() 

这仅适用于等距数据。

1

如果你愿意有一个更强大的数学程序的开销,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

(原点的小开口的东西我已经没有见过,希望很快再次修复。)