0
import matplotlib.pyplot as plt

x_coords = []
y_coords = []


def myFunction(x):
    return (3*(x**2)) + (6*x) + 9


def anotherFunction(x):
    return (x***3) + (x**2) + x


def getCoords(fun, num):
    for n in range(num):
        x_coords.append(n)
        y_coords.append(fun(n))


def draw_graph(x, y):
    plt.plot(x, y, marker="o")
    plt.show()


if __name__ == "__main__":
    # myFunction needs an argument,
    # getCoords provides it as num
    getCoords(myFunction(), 42)
    draw_graph(x_coords, y_coords)
    getCoords(anotherFunction(), 69)
    draw_graph(x_coords, y_coords)

I want to plot multiple arbitrary math functions while (ideally?) reusing code for getting coordinates and plotting them. Would there be a better way to restructure this, or am I super close to getting this working?

This question has great answers, but I'm not sure how to integrate them.

seph
  • 7
  • 1
  • 2
  • Also, I forgot that the x/y coord list needs to be cleared for each plot: `x_coords.clear()` & `y_coords.clear()` – seph Oct 02 '19 at 15:46

1 Answers1

1

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))
  • 1
    I see that now. Python always surprises me with its flexibility. And thank you for introducing ```yield``` – seph Oct 01 '19 at 16:06