Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.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()

Here is the graph (including unwanted vertical lines):

enter image description here

Can I remove the vertical lines without setting appropriate gaps into the x intervals?

like image 899
Astrophe Avatar asked Mar 16 '17 15:03

Astrophe


People also ask

How do I make lines disappear in Matplotlib?

To hide lines in Matplotlib, we can use line. remove() method.

Is PLT show () blocking?

show() and plt. draw() are unnecessary and / or blocking in one way or the other.

What does %Matplotlib mean in Python?

What Does Matplotlib Mean? Matplotlib is a plotting library available for the Python programming language as a component of NumPy, a big data numerical handling resource. Matplotlib uses an object oriented API to embed plots in Python applications.


4 Answers

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)

enter image description here

like image 108
Suever Avatar answered Oct 12 '22 20:10

Suever


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.

like image 38
ImportanceOfBeingErnest Avatar answered Oct 12 '22 21:10

ImportanceOfBeingErnest


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)

enter image description here

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

like image 23
kcrisman Avatar answered Oct 12 '22 21:10

kcrisman


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

like image 1
Gustav Rasmussen Avatar answered Oct 12 '22 20:10

Gustav Rasmussen