🐸

Python の標準ライブラリ turtle で関数を描く

2020/09/25に公開

turtle とは

Python 標準の描画ライブラリです。
昔にはじめて Python のリファレンスを呼んだときに、なんだこれは!こんな簡単に絵が書けるのか!と驚いた記憶があります。

Python も 3 になって久しいけどまだ有るんだろうかとリファレンスを覗くとしっかりあったので、それを使って絵を描く記事を書くことにしました。
公式リファレンスへのリンク

turtle の概念

ポイントは ペンで絵を書いている ということです。
ペンをこれさえわかれば、何か書いてみるのはできます。

とりあえず半径200の円でも描いてみましょう。

y = r \cos(\theta)\\ x = r \sin(\theta)

import turtle
import numpy

if __name__ == "__main__":
    # 半径の設定
    r = 200

    # ペンを最初の位置にもっていく
    turtle.penup()
    turtle.goto(r, 0)
    turtle.pendown()

    # 円を描く
    for th in numpy.linspace(0, 2 * numpy.pi, 200):
        x = r * numpy.cos(th)
        y = r * numpy.sin(th)
        turtle.goto(x, y)

    # 停止する
    turtle.done()

すると、こういう感じで絵が描かれます。

円の描画

螺旋を描く

それでは、ちょっと凝ったものも描いて見ましょう。

plot_axis() 関数でX軸・Y軸を描いて、螺旋状の絵を描きます。

x = a * e^{b \theta} \cos(\theta)\\ y = a * e^{b \theta} \sin(\theta)
import turtle
import numpy
import time

def plot_axis(size=300):
    turtle.penup()
    turtle.goto(0, -size)
    turtle.pendown()
    turtle.goto(0, size)

    turtle.penup()
    turtle.goto(-size, 0)
    turtle.pendown()
    turtle.goto(size, 0)


def spiral(a, b):
    for th in numpy.linspace(0, 15 * numpy.pi, 500):
        x = a * numpy.exp(b * th) * numpy.cos(th)
        y = a * numpy.exp(b * th) * numpy.sin(th)
        turtle.goto(x, y)

if __name__ == "__main__":
    r = 200

    plot_axis()

    turtle.penup()
    turtle.goto(r, 0)
    turtle.pendown()
    spiral(5, 0.07)
    turtle.done()

すると、こういう感じで軸と螺旋が描かれます。

まとめ

ただ絵が描かれるだけじゃなくて、描く様子もアニメーションで表示されるすぐれものなので、いろんな描画をさせて楽しんでみてください。

Discussion