0

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.

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158

2 Answers2

0

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()
The Photon
  • 1,242
  • 1
  • 9
  • 12
0

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()
Rubisko
  • 46
  • 5