Skip to main content
 首页 » 编程设计

python之如何使用 Python turtle 绘制函数

2025年02月15日7lidabo

我正在尝试创建一个 python 脚本,它允许我使用 turtle 来绘制类似 y = 0.5x + 3 的函数。如何做到这一点?我目前的做法是:

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

请您参考如下方法:

您可以绘制一些轴,然后在 x 坐标范围内绘制 y:

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() 

或者,您可以切换到 matplotlib(和 numpy)而忘记 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() 

并根据您的喜好进行定制。