Search code examples
pythonmathgraphing

python isn't plotting the "tangent" function correctly


I'm trying to plot the general tangent function onto matplotlib in Python but it is coming out incorrectly.

The function I'm trying to plot is: $$ f(x) = A tan( \frac{2\pi}{\lambda} x - \phi ) $$


import numpy as np
import math
import matplotlib.pyplot as plt
import tkinter

f = lambda x, A, lambda_, phi: A * math.sin( ((2 * math.pi) / lambda_) * x - phi)
g = lambda x, A, lambda_, phi: A * math.cos( ((2 * math.pi) / lambda_) * x - phi)
h = lambda x, A, lambda_, phi: f(x, A, lambda_, phi) / g(x, A, lambda_, phi)

def generate_graph(A, lambda_, Phi):
    plt.figure()
    x = np.arange(-.95, .95, 0.005)
    #plt.plot(x, [f(k, A, lambda_, Phi) for k in x], color='red')
    #plt.plot(x, [g(k, A, lambda_, Phi) for k in x], color='blue')
    plt.plt(x, [h(k, A, lambda_, Phi) for k in x], color='green')
    plt.show()

A = 1 #amplitude
lambda_ = 3 #wavelength
Phi = 0 #phase shift

generate_graph(A, lambda_, Phi)

It's supposed to look like this: correct

But it ends up looking like this: wrong


Solution

  • This happens due to singularities of the tangent function (i.e., having x values around those points). A quick fix would be to restrict the y-axis with, e.g.,

    plt.ylim(-40, 40)
    

    giving

    enter image description here