How do I exclude certain values when drawing a graph?

111 Views Asked by At

i just started learning python matplotlib. i want draw y = 1/x linespace in python matplotlib.pyplot. but as you see the picture, asymptote show up in graph. i want to remove the asymptote. how to make this? thank you for reading my question.

https://i.stack.imgur.com/P9LPO.png

here is my code

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-5,5,1000)
y = 1 /x
fig, ax = plt.subplots()
ax.plot(x,y,linewidth=2.0)
ax.set(xticks=np.arange(-6,6), ylim=(-20,20))
plt.show()

just try exclude x =0. but it feels difficult and i think there is another way.

please explain me or show code.

2

There are 2 best solutions below

1
The Photon On

Just draw two separate graphs, one for x from -5 to -0.01, and one for x from 0.01 to 5. If you want them to come out the same color, be sure to specify the color explicitly.

import matplotlib.pyplot as plt
import numpy as np

x1 = np.linspace(-5, -0.01,500)
x2 = np.linspace(0.01, 5,500)
y1 = 1 / x1
y2 = 1 / x2

fig, ax = plt.subplots()
ax.plot(x1,y1, c='blue', linewidth=2.0)
ax.plot(x2,y2, c='blue', linewidth=2.0)
ax.set(xticks=np.arange(-6,6), ylim=(-20,20))
plt.show()
1
Rubisko On

There isn't technically another way, since the y=1/x graph consists of two separate branches, and in your example code you are trying to draw them in one line. So what you have called an asymptote is actually the line, that connects the points(-0.01, -100) and (0.01, 100) on your graph.

So yes, you should exclude the zero manually:

import matplotlib.pyplot as plt
import numpy as np

x1 = np.linspace(-5,-0.01,1000)
x2 = np.linspace(0.01,5,1000)
fig, ax = plt.subplots()
ax.plot(x1,1/x1,linewidth=2.0)
ax.plot(x2,1/x2,linewidth=2.0)
ax.set(xticks=np.arange(-6,6), ylim=(-20,20))
plt.show()