如何使用Python Turtle绘制折线图?

时间:2019-10-18 02:39:55

标签: python graph 2d turtle-graphics

这个问题可能之前曾被问过,但是对我来说不起作用。有什么方法可以使用python turtle绘制折线图吗?

我不知道从哪里开始

from turtle import Turtle

谢谢您的帮助。

3 个答案:

答案 0 :(得分:1)

  

“极有可能”,它甚至可以做得更简单(例如,不使用x2   和y2变量,但我不确定)

如果我们的目标是使用turtle绘制一个简单的线函数,我们可以变得更简单:

from turtle import Turtle, Screen
from math import pi, sin

def draw_wave(frequency=1):
    angle = 0

    while angle < 2 * pi:
        turtle.goto(angle, sin(angle * frequency))
        angle += 0.05

screen = Screen()
screen.setworldcoordinates(0, -1.25, 2 * pi, 1.25)

turtle = Turtle()

draw_wave(2)

turtle.hideturtle()
screen.exitonclick()

然后根据需要修饰(轴等)。

答案 1 :(得分:0)

我不确定我理解“折线图”,https://en.wikipedia.org/wiki/Line_graph还是https://en.wikipedia.org/wiki/Line_chart是什么意思吗?对于第二种情况,例如,可以使用以下简化代码完成窦功能。

import turtle as tr
import math as m

x0, y0 = -300, 275  # The point near the upper left corner of the Turtle screen - virtual origin of coordinates
Y0 = -y0 + 100  # The reference vertical coordinate for the second function
A0 = 100  # The amplitude of sinus function
f0 = 80   # 1/frequency (reverse frequency)

def draw1():
   x1 = 0
   y1 = A0 - A0 * m.sin(x1/f0)
   tr.goto(x0 + x1, y0 - y1)
   tr.down()
   tr.dot(size = 1)
   for x2 in range(abs(x0)*2):
      y2 = A0 - A0 * m.sin(x1/f0)
      tr.goto(x0 + x2, y0 - y2)
      tr.dot(size = 1)
      x1, y1 = x2, y2

def draw2(f0):
   x1 = 0
   y1 = Y0 + A0 * m.sin(x1/f0)
   tr.goto(x0 + x1, y1)
   tr.down()
   tr.dot(size = 1)
   for x2 in range(abs(x0)*2):
      y2 = Y0 + A0 * m.sin(x1/f0)
      tr.goto(x0 + x2, y2)
      tr.dot(size = 1)
      x1, y1 = x2, y2

tr.speed('fastest')
tr.up()
tr.goto(x0, y0)
tr.hideturtle()
tr.color('red')
draw1()  # The pivot point - the virtual origin of coordinates (x0 and y0)

tr.up()
tr.goto(x0,y0)
tr.color('blue')
draw2(f0/2)  # The pivot point - x0 and Y0
input()      # waiting for the <Enter> press in the console window

“极有可能”,它甚至可以做得更简单(例如,没有x2y2变量,但我不确定)-我从Tkinter画布上绘制此方法。 而且这种方法可能适用于第一种情况(当然,要进行某种修改)。

答案 2 :(得分:0)

我认为您想绘制线性方程式:mx + b

import turtle as t
a = t.window_width() / 2
def graph(m_x, m_y, b):
    x = [i for i in range(int(-a), int(a), m_x)]
    return list(zip(x, map(lambda x_val: ((m_x / m_y) * x_val) + b, x)))
for x, y in graph(1, 10, 0):
    t.goto(x, y)
t.mainloop()