1

I want to plot the following function in matplotlib without any vertical asymptotes:

f(x) = 1/(x - 1)

Is there an exclusion function in matplotlib that can mask/hide the asymptotes similar to Exlusions in Mathematica

The answer here doesn't seem to help.

OTheDev
  • 2,916
  • 2
  • 4
  • 20
RUNN
  • 77
  • 7
  • At what stage do you consider them worth hiding? Would this be gradient dependent based on the proximity to the asymptote? If that's the case, you can slice both the ```fx``` and ```x``` lists / arrays, remove any points with a gradient magnitude above a specified value, and them put the lists back together again before plotting. – ChaddRobertson Apr 10 '22 at 14:02
  • It's not gradient-dependent. I want to hide them when the denominator is zero, i.e., when x - 1 = 0. – RUNN Apr 10 '22 at 14:51
  • You can attempt to determine the position of all asymptotes and then split your lists up into those representative of a piecewise function (a list of lists; a matrix). This would allow you to loop through your matrix, plotting each piecewise list separately. This will ensure that points over the discontinuities will not be joined. – ChaddRobertson Apr 10 '22 at 15:24

1 Answers1

1

I assumed you only tried the first answer. When you read a stack overflow question with multiple answers and the first is not working for you, you should try the next one.

The idea behind these solution is to mask out values that do not interests you. Here you see:

  • the original plot with the ugly asymptote.
  • first method: we know precisely the location of the asymptote, x=1. Hence, we can hide all y values in a small region near x=1.
  • second method: near the asymptotes values tends to infinity. We can hide all values that are greater (or smaller) than some threshold.

There are definitely other ways to solve this problem, but the two previous one are quick and effective for simple plots.

import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0.5, 1.5, 1000)
y = 1 / (x - 1)

f, ax = plt.subplots(2, 2)
ax[0, 0].plot(x, y)
ax[0, 0].set_title("Original")

y2 = y.copy()
# select all values of y2 where x > 0.99
# and x < 1.01. You can play with these numbers
# to get the desired output.
y2[(x > 0.99) & (x < 1.01)] = np.nan
ax[0, 1].plot(x, y2)
ax[0, 1].set_title("First method")

y3 = y.copy()
# hide all y3 values whose absolute value is
# greater than 250. Again, you can change this
# number to get the desired output.
y3[y3 > 250] = np.nan
y3[y3 < -250] = np.nan
ax[1, 0].plot(x, y3)
ax[1, 0].set_title("Second method")

plt.tight_layout()
plt.show()

enter image description here

Davide_sd
  • 10,578
  • 3
  • 18
  • 30