Kodewick
Start learning →

Python Turtle Butterfly (Butterfly Curve)

No wing drawn by hand: one formula gives every point, and the turtle joins them into a butterfly.

Python Turtle Butterfly (Butterfly Curve)
The full code (27 lines)
import turtle
import math

screen = turtle.Screen()
screen.bgcolor("#fdf6ec")
t = turtle.Turtle()
t.hideturtle()
t.speed(0)
t.pensize(2)
turtle.tracer(0)

size = 40
colors = ["#e4572e", "#f3a712", "#29335c", "#669bbc", "#a23b72"]

# The butterfly curve: r = e^cos(a) - 2cos(4a) - sin(a/12)^5
t.penup()
for i in range(3000):
    a = i * 24 * math.pi / 3000
    r = math.exp(math.cos(a)) - 2 * math.cos(4 * a) - math.sin(a / 12) ** 5
    x = size * r * math.sin(a)
    y = size * r * math.cos(a)
    t.pencolor(colors[i * len(colors) // 3000])
    t.goto(x, y - 20)
    t.pendown()

turtle.update()
turtle.done()

How it is drawn

The butterfly curve is a polar curve: the angle a goes from 0 to 24π, and each angle gives a distance from the middle, r = e^cos(a) - 2cos(4a) - sin(a/12)^5.

Polar to the turtle's x and y: x = r * sin(a), y = r * cos(a), times size to make it bigger. With sin for x and cos for y, the butterfly stands upright.

The turtle goes to the first point with the pen up, then goto each point with the pen down. The color depends on how far along it is, so the wings change color as they go round.

turtle.tracer(0) hides the drawing until turtle.update() shows it all at once: 3,000 points in a moment.

Questions

Why 24π?

The formula has sin(a/12), which needs 24π to go all the way round; with 2π you only get a small part of the wings.

Can I draw other shapes?

Change the formula: r = sin(4a), for one, is a four-petal rose. Only the r line changes.

Try another