首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用Python turtle绘制函数

如何使用Python turtle绘制函数
EN

Stack Overflow用户
提问于 2017-09-22 02:55:37
回答 2查看 12.2K关注 0票数 3

我正在尝试创建一个python脚本,它将允许我使用turtle来绘制y= 0.5x + 3这样的函数。我目前的方法是:

代码语言:javascript
复制
import turtle
ivy = turtle.Turtle()


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

plotter(x=20)
EN

回答 2

Stack Overflow用户

发布于 2017-09-22 08:17:41

您可以绘制一些轴,然后在一系列x坐标上绘制y:

代码语言:javascript
复制
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:

代码语言:javascript
复制
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()

并根据您的心意进行定制。

票数 3
EN

Stack Overflow用户

发布于 2018-08-05 08:42:44

代码语言:javascript
复制
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)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46351278

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档