2017-03-16 64 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

(原點的小開口的東西我已經沒有見過,希望很快再次修復。)