Article 13 of 20 · 7 min read

How to draw fractals with Python

Three short, complete Python programs that draw the Koch snowflake, the Barnsley fern and the Mandelbrot set, explained line by line for beginners.

Watching a fractal appear on your own screen from twenty lines of code is a special pleasure, and Python, free and readable, is ideal for the experiment. In this guide you will write three programs, each using a different idea for making fractals: recursion, the chaos game and escape-time iteration.

It helps to know what a variable and a loop are. Each program is complete: copy it into a file, run it, and a picture window should open.

Setting up

You need Python 3 and two libraries: numpy for fast arithmetic on whole arrays of numbers, and matplotlib for drawing. Open a terminal (Command Prompt on Windows) and type:

pip install numpy matplotlib

If pip is not found, try python3 -m pip install numpy matplotlib instead. Save each program in a file such as koch.py and run it with python3 koch.py, or use the Run button of an editor such as IDLE or Thonny.

1. The Koch snowflake by recursion

The Koch curve is built by a single rule: take a line segment, divide it into thirds, and replace the middle third with two sides of an equilateral triangle pointing outwards. Then apply the same rule to each of the four new segments, and so on. A function that calls itself is the natural way to express "and so on".

import numpy as np
import matplotlib.pyplot as plt

def koch(p, q, depth):
    """Return the points of a Koch curve from p to q (without q)."""
    if depth == 0:
        return [p]
    a = p + (q - p) / 3
    b = p + (q - p) * 2 / 3
    turn = np.array([[0.5, -np.sqrt(3) / 2], [np.sqrt(3) / 2, 0.5]])
    peak = a + turn @ (b - a)        # rotate the middle third by 60 degrees
    points = []
    for s, e in [(p, a), (a, peak), (peak, b), (b, q)]:
        points += koch(s, e, depth - 1)
    return points

depth = 4
corners = [np.array([0.0, 0.0]), np.array([0.5, np.sqrt(3) / 2]), np.array([1.0, 0.0])]
points = []
for i in range(3):
    points += koch(corners[i], corners[(i + 1) % 3], depth)
points.append(corners[0])            # close the loop

x, y = zip(*points)
plt.figure(figsize=(6, 6))
plt.plot(x, y, color="teal", linewidth=0.8)
plt.axis("equal")
plt.axis("off")
plt.show()

The function koch(p, q, depth) receives two points as numpy arrays. If depth is 0 it simply returns the starting point; this is the base case that stops the recursion. Otherwise it computes the two points at one third and two thirds of the way, finds the tip of the bump by rotating the middle third through 60° with a rotation matrix, and calls itself on the four smaller segments. The main part runs this on the three sides of a triangle to make the snowflake.

A Koch snowflake drawn as a thin cyan line on a dark background at iteration 5.
The Koch snowflake at iteration 5. Each step multiplies the number of segments by 4, so the outline here has 3 × 45 = 3072 segments.

Try changing depth; beyond 6 or 7 the extra detail is smaller than a pixel. If your snowflake comes out with the bumps pointing inwards, the corners are being visited in the opposite direction; reverse their order. Python's built-in turtle module is a pleasant alternative: a recursive function that turns 60°, −120° and 60° between its four calls draws the curve while you watch.

2. The Barnsley fern by the chaos game

The second method needs no recursion. Michael Barnsley showed in the 1980s that a realistic fern is the attractor of just four affine maps, simple rules that shrink, rotate and shift a point. You start with one point, repeatedly pick one of the maps at random, apply it, and plot where the point lands.

import numpy as np
import matplotlib.pyplot as plt

# Each row: a, b, c, d, e, f for the map (x, y) -> (a*x + b*y + e, c*x + d*y + f)
maps = np.array([
    [0.00,  0.00,  0.00, 0.16, 0.0, 0.00],   # stem
    [0.85,  0.04, -0.04, 0.85, 0.0, 1.60],   # smaller copy of the whole fern
    [0.20, -0.26,  0.23, 0.22, 0.0, 1.60],   # largest leaflet on one side
    [-0.15, 0.28,  0.26, 0.24, 0.0, 0.44],   # largest leaflet on the other side
])
probs = [0.01, 0.85, 0.07, 0.07]

n = 100_000
choices = np.random.choice(4, size=n, p=probs)
xs, ys = np.zeros(n), np.zeros(n)
x, y = 0.0, 0.0
for i in range(n):
    a, b, c, d, e, f = maps[choices[i]]
    x, y = a * x + b * y + e, c * x + d * y + f
    xs[i], ys[i] = x, y

plt.figure(figsize=(5, 8))
plt.scatter(xs, ys, s=0.1, color="green")
plt.axis("equal")
plt.axis("off")
plt.show()

Each row of maps holds six numbers for one map. The first map, chosen 1% of the time, squashes everything onto the stem. The second, chosen 85% of the time, makes a slightly smaller, slightly tilted copy of the whole fern; this is why the leaflets get smaller towards the tip. The third and fourth, 7% each, produce the two lowest leaflets. The probabilities 0.01, 0.85, 0.07 and 0.07 must add up to 1, and np.random.choice uses them to pick a map for every step in advance.

A Barnsley fern made of many small glowing cyan points on a dark background.
The Barnsley fern: every leaflet is a smaller copy of the whole frond, produced by just four affine maps chosen at random.

Try equal probabilities of 0.25: the shape is mathematically the same, but points are wasted on the stem and the leaflets look patchy. Then alter one number in the second row, such as 0.04, and watch the fern curl. A common mistake is to update x and then use the new x to calculate y; the program avoids this by assigning both on one line.

3. The Mandelbrot set with numpy

For each point c of the complex plane, start with z = 0 and repeat z → z2 + c. If |z| ever exceeds 2, the sequence is certain to fly off to infinity and c is outside the set. Counting how many steps that takes gives each pixel its colour. Instead of looping over the 480,000 pixels one by one, numpy lets you treat the whole grid as a single array.

import numpy as np
import matplotlib.pyplot as plt

width, height, max_iter = 800, 600, 100
x = np.linspace(-2.5, 1.0, width)
y = np.linspace(-1.3125, 1.3125, height)
c = x[np.newaxis, :] + 1j * y[:, np.newaxis]   # one complex number per pixel

z = np.zeros_like(c)
counts = np.zeros(c.shape, dtype=int)          # iterations survived
for n in range(max_iter):
    inside = np.abs(z) <= 2                    # points that have not escaped
    z[inside] = z[inside] ** 2 + c[inside]
    counts[inside] += 1

plt.figure(figsize=(8, 6))
plt.imshow(counts, extent=(-2.5, 1.0, -1.3125, 1.3125),
           cmap="magma", origin="lower")
plt.axis("off")
plt.show()

The line that builds c combines 800 real parts and 600 imaginary parts into a grid of complex numbers; 1j is Python's i. In each of the 100 rounds, inside marks the points that have not yet escaped, only those are updated, and their counters go up by one. Points still inside after 100 rounds are treated as members of the set. The ranges match the 4:3 shape of the grid; otherwise the set looks stretched.

The Mandelbrot set rendered with smooth colouring in shades of violet and gold on a dark background.
The Mandelbrot set with smooth colouring. The program above uses whole iteration counts, which produce visible bands; smooth colouring blends between them.

Raise max_iter to 500 to sharpen the boundary, at the cost of speed. To zoom, shrink both ranges around an interesting point, for example x from −0.75 to −0.73 and y from 0.10 to 0.115, and increase max_iter, because finer detail needs more steps. Try other colour maps such as "twilight". The smooth colouring in the illustration replaces the whole number of steps n with n + 1 − log(log|z|)/log 2, which removes the bands.

Typical mistakes

Where to go next

Compare your output with the interactive Mandelbrot explorer and the chaos game. The lessons on iterated function systems and the Mandelbrot set explain the mathematics behind the second and third programs.

Cite this page
APA

Fractalist. (2026). How to draw fractals with Python. ForeFractal. https://forefractal.com/articles/how-to-draw-fractals-with-python/

MLA

Fractalist. “How to draw fractals with Python.” ForeFractal, 2026, https://forefractal.com/articles/how-to-draw-fractals-with-python/. Accessed .

BibTeX
@misc{forefractal-articles-how-to-draw-fractals-with-python,
  author = {Fractalist},
  title = {How to draw fractals with Python},
  year = {2026},
  howpublished = {\url{https://forefractal.com/articles/how-to-draw-fractals-with-python/}},
  note = {ForeFractal}
}