Python: Graphing with turtles
Edited
You can use the turtle
tool to make graphs and data visualizations.
Graphing a Line
Let's say we wanted to draw a simple line, the kind that you may have seen in math class—described by a function that looks like this: y = mx + b.
We could do that with the turtle tool by defining x
and y
as variables in python. x
will be defined as a domain of points that we want to graph across.
for i in range(-250, 250):
#define x in terms of i
x = i/10.0
Then, we can define y
using the line equation. In this case, m = 2 and b = 3.
# define y in terms of x
y = 2x + 3
Once we have x
and y
defined as the coordinates of the next point on our graph, we can tell the turtle to go to that location to graph our function.
# check if y is a number, then goto(x, y)
if(not math.isnan(y)) :
pen.goto(x, y)
pen.pendown()
Here is the full code and demo.
import turtle, math
pen = turtle.Turtle()
pen.penup()
pen.speed(0)
pen.color("blue")
# loop through the domain
for i in range(-100,100) :
# define x in terms of i
x = i/10.0
# define y in terms of x
y = 2*x + 3
# check if y is a number, then goto(x, y)
if(not math.isnan(y)) :
pen.goto(x, y)
pen.pendown()
Graphing a Parabola
Now that you have the concept down, take a look at another example. This time, we will graph a parabola.
import turtle, math
pen = turtle.Turtle()
pen.penup()
pen.speed(0)
pen.color("green")
# loop through the domain
for i in range(-100,100) :
# define x in terms of i
x = i/10.0
# define y in terms of x (our parabola function)
y = x**2 - 100
# check if y is a number, then goto(x,y)
if(not math.isnan(y)) :
pen.goto(x, y)
pen.pendown()