import turtle def points(tup): """ Given a tuple ((x_1, y_1), (x_2, y_2), (x_n, y_n),...) return a function f(x_n): y=y_n. """ return lambda x: dict(tup)[float(x)] class Tools(): """Miscellanous functions for turtle""" def go(self, x, y): """Move cursor to point (x, y) without drawing a line""" self.pu() self.goto(x, y) self.pd() class Arrow(turtle.Pen, Tools): """Custom turtle cursor""" def __init__(self): super(Arrow, self).__init__() self.speed(0) self.shape("triangle") self.shapesize(0.5) class Graph(turtle.Pen, Tools): def __init__(self, canvas, X=10, Y=10): """ Initialization of the graph. Providing the size of the axes if necessary. """ super(Graph, self).__init__() turtle.title("Plot") self.X = X self.Y = Y self.canvas = canvas self.frame = turtle._Screen._root self.axes() self.arrows() def axes(self): """Draw the axes of the coordinate plane""" turtle.setworldcoordinates( -(self.X + 2), -(self.Y + 2), self.X + 2, self.Y + 2) self.hideturtle() self.speed(0) self.go(-self.X, 0) self.fd(self.X * 2) self.go(0, -self.Y) self.lt(90) self.fd(self.Y * 2) def arrows(self): """Draw arrows and labels""" a = Arrow() a.go(self.X, 0) a.write(" x", font=("helvetiva", 16)) b = Arrow() b.lt(90) b.go(0, self.Y) b.write(" y", font=("helvetiva", 16)) def plot(self, function, start, stop, color="blue"): """Plot a function""" medium = 2 / self.X self.color(color) try: self.go(start, function(start)) except ZeroDivisionError: self.go(start, function(start + 1 * medium)) for x in range(int(start / medium), int(stop / medium) + 1): x *= medium try: self.goto(x, function(x)) except ZeroDivisionError: self.go(x, function(x + 1 * medium)) def clean(self): """Clean the canvas redraw axes""" self.reset() self.axes()