Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to plot tan(x) with pyplot and numpy

Code:

import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10000)
plt.plot(x, np.tan(x))
plt.show()

Expected result:

enter image description here

The result I get:

enter image description here

like image 319
snzm Avatar asked Feb 03 '19 18:02

snzm


People also ask

How can I get tan in NumPy?

tan(array[, out]) = ufunc 'tan') : This mathematical function helps user to calculate trigonometric tangent for all x(being the array elements). Parameters : array : [array_like]elements are in radians.

Can we plot graph using NumPy?

For plotting graphs in Python, we will use the Matplotlib library. Matplotlib is used along with NumPy data to plot any type of graph. From matplotlib we use the specific function i.e. pyplot(), which is used to plot two-dimensional data.


1 Answers

There are two issues, I think. The first is about np.linspace, the second about plotting.

np.linspace defaults to returning 50 elements within the given range. So you're plotting 50 points over (0, 10000), meaning the elements are very widely spaced. Also, that range doesn't make a whole lot of sense for the tangent function. I'd use something much smaller, probably +/- 2 * pi.

The second issue is the y-axis. The tangent function diverges to infinity quite quickly at multiples of pi/2, which means you're missing a lot of the interesting behavior by plotting the full y-range. The code below should solve these issues.

x = np.linspace(-2 * np.pi, 2 * np.pi, 1000)
plt.plot(x, np.tan(x))
plt.ylim(-5, 5)

You should see something like this: enter image description here

like image 171
bnaecker Avatar answered Sep 28 '22 07:09

bnaecker