1

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

My Code is:

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 this when it should look like this (desmos). 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!) ?

Secozzi
  • 232
  • 3
  • 9
  • Possible duplicate of https://stackoverflow.com/questions/32726992/how-to-plot-a-math-function-from-string – rassar Oct 24 '19 at 23:33

1 Answers1

1

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: And it works quite well If you want to eliminate the nasty line in between you'll have to change the code to split the graph into two.

Michele Bastione
  • 333
  • 3
  • 13