如何使用Python turtle绘制函数?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (607)

我正在尝试创建一个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)
提问于
用户回答回答于
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)
用户回答回答于

可以绘制一些轴,然后在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)并忘记海龟:

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

扫码关注云+社区

领取腾讯云代金券

年度创作总结 领取年终奖励