pythonstringmatplotlibevaluationmath-functions

# Graphing function from string doesn't evaluate correctly at 0

I'm trying to create a grapher using `matplotlib.pyplot` and want to graph a function that comes like a string

``````import matplotlib.pyplot as mpl
import numpy as np

def plot2D(*args):
mpl.grid(1)
xAxis = np.arange(args[1],args[2],args[3])
def xfunction(x,input):
return eval(input)
print(xfunction(5,args[0]))
mpl.plot(xAxis,xfunction(xAxis,args[0]))
mpl.show()

plot2D("1/(x)",-1,2,0.1)
``````

I want it to plot the function 1/x but it looks like:

When it should look like:

Am I converting the string to a function wrong or can matplotlib even be used to graph functions like that or should I use another library? How would I go about graphing a function like `x\*\*2 + y\*\*2 = 1`? Or functions like `sin(x!)`?

Solution

• There's an intrinsic problem with the function `1/x`: it's not defined in 0. Now, in your code one of the values inside the range is unfortunately 0, and thus it messes up the whole thing big time. All you have to do is change the last line of code to shift the range a little bit, and increase the number of steps in order to get more accurate results: `plot2D("1/x",-1.01,2,0.02)`. This is the plot: If you want to eliminate the nasty line in between you'll have to change the code to split the graph into two.