plotter/graph.py

88 lines
1.8 KiB
Python
Raw Permalink Normal View History

2014-01-14 20:12:07 +01:00
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
2014-04-07 21:46:18 +02:00
init = True
2014-01-14 20:12:07 +01:00
self.color(color)
for x in range(int(start / medium), int(stop / medium) + 1):
x *= medium
try:
2014-04-07 21:46:18 +02:00
if init:
self.go(x, function(x))
init = False
else:
self.goto(x, function(x))
except Exception:
continue
2014-01-14 20:12:07 +01:00
def clean(self):
"""Clean the canvas redraw axes"""
self.reset()
self.axes()