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):
Can I remove the vertical lines without setting appropriate gaps into the x intervals?
To hide lines in Matplotlib, we can use line. remove() method.
show() and plt. draw() are unnecessary and / or blocking in one way or the other.
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.
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)
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.
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.)
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With