Search code examples
pythonfunctionmathparametersarguments

Plotting multiple functions with pyplot, passing functions into functions, & reusing code



I want to plot multiple arbitrary math functions while reusing code for getting coordinates and plotting them.


Solution

  • You have to provide the function itself and not the call to it.

    getCoords(myFunction, 42)
    getCoords(anotherFunction, 69)
    

    You could restructure to something like this. Having a dedicated function to produce the coordinates and a dedicated function to draw them:

    def myFunction(x):
        return (3*(x**2)) + (6*x) + 9
    
    
    def get_coords(fun, num):
        for n in range(num):
            yield n, fun(n)
    
    
    def draw_graph(coordinates):
        for x, y in coordinates:
            plt.plot(x, y, marker="o")
        plt.show()
    
    
    draw_graph(get_coords(myFunction, 45))