graphing an equation with matplotlib

前端 未结 3 1610
孤城傲影
孤城傲影 2021-01-30 10:54

I\'m trying to make a function that will graph whatever formula I tell it to.

import numpy as np  
import matplotlib.pyplot as plt  
def graph(formula, x_range):         


        
3条回答
  •  天命终不由人
    2021-01-30 11:19

    This is because in line

    graph(x**3+2*x-4, range(-10, 11))
    

    x is not defined.

    The easiest way is to pass the function you want to plot as a string and use eval to evaluate it as an expression.

    So your code with minimal modifications will be

    import numpy as np  
    import matplotlib.pyplot as plt  
    def graph(formula, x_range):  
        x = np.array(x_range)  
        y = eval(formula)
        plt.plot(x, y)  
        plt.show()
    

    and you can call it as

    graph('x**3+2*x-4', range(-10, 11))
    

提交回复
热议问题