4

I am trying to create a python script that will allow me use turtle to plot a function like y = 0.5x + 3. How can this be done? My current approach is:

import turtle
ivy = turtle.Turtle()


def plotter(x):
    y = (0.5 * x) + 3
    ivy.goto(0, y)

plotter(x=20)
cdlane
  • 40,441
  • 5
  • 32
  • 81

2 Answers2

2

You could draw some axes and then plot y over a range of x coordinates:

from turtle import Turtle, Screen

WIDTH, HEIGHT = 20, 15  # coordinate system size

def plotter(turtle, x_range):
    turtle.penup()

    for x in x_range:
        y = x / 2 + 3
        ivy.goto(x, y)
        turtle.pendown()

def axis(turtle, distance, tick):
    position = turtle.position()
    turtle.pendown()

    for _ in range(0, distance // 2, tick):
        turtle.forward(tick)
        turtle.dot()

    turtle.setposition(position)

    for _ in range(0, distance // 2, tick):
        turtle.backward(tick)
        turtle.dot()

screen = Screen()
screen.setworldcoordinates(-WIDTH/2, -HEIGHT/2, WIDTH//2, HEIGHT/2)

ivy = Turtle(visible=False)
ivy.speed('fastest')
ivy.penup()
axis(ivy, WIDTH, 1)

ivy.penup()
ivy.home()
ivy.setheading(90)
axis(ivy, HEIGHT, 1)

plotter(ivy, range(-WIDTH//2, WIDTH//2))

screen.exitonclick()

enter image description here

Or, you could switch to matplotlib (and numpy) and forget turtle:

import numpy as np
import matplotlib.pyplot as plt

def f(x):
    return x / 2 + 3

t = np.arange(-10, 10, 0.5)

plt.plot(t, f(t))

plt.show()

enter image description here

And customize to your heart's content.

cdlane
  • 40,441
  • 5
  • 32
  • 81
0
from turtle import *

ht(); speed(0)
color('green'); width(1)

for i in range(4): # axes
    fd(80); bk(80); rt(90)

color('red'); width(2)
pu(); goto(-50, -70); pd()

for x in range(-50, 30):
    y = 2*x + 30
    goto(x, y)
Yehuda Katz
  • 177
  • 1
  • 8
  • 3
    While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. – Nic3500 Aug 05 '18 at 01:16