Home > OS >  Python-Matplotlib Plotting with infiniite f(x) values
Python-Matplotlib Plotting with infiniite f(x) values

Time:05-24

I am trying to graph the tan function in matplotlib. The tan function goes to infinity when the value inserted is pi/2. The problem is that I dont know how to deal with infinite numbers in Matplotlib or in turn, infinitly small ranges to be able to plot it. One of the problems is the line that goes down, to try to connect the last dot drawn up top, with the first after pi/2

import matplotlib.pyplot as plt
import numpy

x_values = numpy.linspace(-5,5,num=1000)
y_values = numpy.tan(x_values)
plt.plot(x_values, y_values)
plt.show()

This is the output:

Image created by Matplotlib

This is because this function gets 1000 points to plot, not infinite points, but it doesn't create the image that I want, I want an image like the one that a graphic calculator would produce. What can I do?

CodePudding user response:

How to plot a discontinuous function

import numpy as np
from numpy import pi, nan
import matplotlib.pyplot as plt

start, stop, num, eps = -5, 5, 200, 0.003
data = np.linspace(start, stop, num)

shift = (data   pi/2) % pi
data = data[(eps < shift) & (shift < pi - eps)]
asymptotes = np.r_[start:stop:pi] - (start   pi/2) % pi   pi

xx = np.r_[data, asymptotes]
yy = np.r_[np.tan(data), [nan]*len(asymptotes)]
order = xx.argsort()   

xlim = [start, stop]
ylim = [-25, 25]

plt.figure(figsize=(8,12))
plt.xlim(xlim)
plt.ylim(ylim)

plt.plot([asymptotes]*2, 
         [[i]*len(asymptotes) for i in ylim], 
         'k--', linewidth=1)

plt.plot(xx[order], yy[order])
plt.show()
  • asymptotes - discontinuity points of the tangent function
  • eps - a radius of the excluded neighborhood around the discontinuity points
  • shift - distance from data to nearest breakpoints on the left

enter image description here

  • Related