Good day! I want to build a hyperbole with matplotlib, for example. There is the following code:

import matplotlib.pyplot as plt import pylab, math xmin = -200 xmax = 200 dx = 0.1 xlist = [float(x) for x in range(xmin,xmax)] ylist = [float(1/x) for x in range(xmin,xmax)] ax = plt.gca() ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') ax.xaxis.set_ticks_position('bottom') ax.spines['bottom'].set_position(('data',0)) ax.yaxis.set_ticks_position('left') ax.spines['left'].set_position(('data',0)) plt.grid(True) plt.title('График функции ') pylab.plot(xlist,ylist) pylab.savefig('123.png') 

Example of work on the picture As you can see, there is a segment between the two branches of the function. I know that this is due to the fact that there is a value of the extreme points of the branches, and the raft connects them. But I do not need it, I need to get a normal schedule. If this schedule were always hyperbole, it would be normal. But this schedule can be any schedule with a gap. How to avoid this segment? I saw ways, but there were used additional packages (numpy), I do not want to pull them into this code [ enter image description here ]

1 answer 1

To begin with, I repeat that matplotlib already uses numpy inside itself, so that it will not be avoided. However, here is the first version without numpy in the main code:

 import matplotlib.pyplot as plt import decimal # Это замена np.arange def arange(start, stop, step): while start < stop: yield start start += decimal.Decimal(step) hyperbola = lambda x: 1 / x def asymptote_checker(argument, function): try: function(argument) return True except ZeroDivisionError: return False xmin = -20 xmax = 20 dx = 0.1 xlist = [round(x, 4) for x in arange(xmin, xmax, dx)] ylist = [hyperbola(x) if asymptote_checker(x, hyperbola) else float('nan') for x in xlist] plt.plot(xlist, ylist) plt.show() 

With numpy will be shorter:

 import matplotlib.pyplot as plt import decimal import numpy as np xmin = -20 xmax = 20 dx = 0.1 xlist = np.around(np.arange(xmin, xmax, dx), decimals=4) ylist = 1 / xlist plt.plot(xlist, ylist) plt.show() 

A couple of common points for both versions: the numbers in the xlist instead of zero can suddenly turn into garbage like 7.0485345e-13 or something that will spill over into a huge value along the Oy axis. The second point - matplotlib ignores (and does not connect dots) numbers like + inf, -inf, NaN - you can mark them with your hands, trust it with numpy or use the numpy masked array .