Omit joining lines in matplotlib plot e.g. y = tan(x)

前端 未结 4 1052
囚心锁ツ
囚心锁ツ 2020-12-04 01:48

I have the graph y = tan(x) and I want to remove the vertical lines (see below).

Here is my code:

import numpy as np
import matplotlib.p         


        
相关标签:
4条回答
  • 2020-12-04 02:32

    One could use the definition of the tangent to filter out those points where the cosine of x is close enough to 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()
    

    This works for equally spaced data only.

    0 讨论(0)
  • 2020-12-04 02:36

    You can check the difference between successive data points using diff and then identify where the difference is negative and replace these values with NaN to create a visual break in the plotted line

    # 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)
    

    0 讨论(0)
  • 2020-12-04 02:47

    If you're willing to have the overhead of a more powerful mathematical program, SageMath can help with this:

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

    (The little opening at the origin is something I've not seen before, hopefully fixed again soon.)

    0 讨论(0)
  • 2020-12-04 02:47

    Use the definition of tan, sin/cos. The vertical asymptotes will happen when cos = 0, so write a conditional statement such as: if cos(x) != 0: plt.plot(x, np.tan(x))

    0 讨论(0)
提交回复
热议问题