# How to generate reproducible branching patterns for pen plotting with Python

**URL:** <https://forum.plotterfolk.com/t/how-to-generate-reproducible-branching-patterns-for-pen-plotting-with-python/95>\
**Category:** Generative Art & Creative Coding\
**Tags:** svg, generative-art, creative-coding, pen-plotting\
**Created:** [November 3, 2026, 8:12pm UTC](https://forum.plotterfolk.com/t/how-to-generate-reproducible-branching-patterns-for-pen-plotting-with-python/95 "2026-11-03T20:12:38Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![rubencio](https://forum.plotterfolk.com/user_avatar/forum.plotterfolk.com/rubencio/32/11_2.png) [@rubencio](https://forum.plotterfolk.com/u/rubencio)\
**Post date:** [November 3, 2026, 8:12pm UTC](https://forum.plotterfolk.com/t/how-to-generate-reproducible-branching-patterns-for-pen-plotting-with-python/95/1 "2026-11-03T20:12:38Z")

</div>

Branching structures appear throughout nature.

Trees, river networks, veins and many organic forms can be described through repeated divisions.

In generative art, a branching system can emerge from a simple geometric rule: draw a segment, divide it into two smaller segments and repeat.

The result can be especially interesting for pen plotting because the entire composition can be represented using line geometry.

No filled shapes, raster images or complex SVG effects are necessary.

**The challenge is to create a branching system that is reproducible, physically manageable and suitable for export as real SVG paths.**

This tutorial builds a simple branching drawing using Python.

No external libraries are required.

## 1. Define the branching rule

We begin with one line segment.

At its endpoint, the algorithm creates two new branches.

Each new branch:

- Starts where the previous segment ended.
- Is shorter than its parent.
- Turns by an angle relative to the previous direction.
- Repeats the same operation until the maximum depth is reached.

This is a recursive process.

The system becomes more complex as the number of levels increases.

However, complexity can grow rapidly.

A branching drawing with two children per segment produces many more paths with each additional level.

For a pen plotter, this matters because every independent segment may contribute to the total number of plotted paths and pen movements.

## 2. Choose the page format

We’ll use an A4 document:

- Width: 210 mm.
- Height: 297 mm.

The branching drawing will begin near the bottom of the page and grow upward.

Our initial position is:

`x = 105 mm`

`y = 270 mm`

In SVG coordinates, positive `y` normally extends downward on the page.

Therefore, an angle of `-90°` points upward.

The starting segment will have a length of 48 mm.

These values are chosen for this example.

They are not universal requirements for branching artwork.

## 3. Control the parameters

The most important parameters are:

| Parameter | Function |
| --- | --- |
| Random seed | Makes the same generated variation reproducible |
| Maximum depth | Controls the number of branching levels |
| Starting length | Controls the initial segment |
| Branch reduction | Makes successive segments shorter |
| Branch angle | Controls how widely the structure spreads |
| Stroke width | Controls SVG preview appearance |

We will introduce small random variations in branch length and direction.

However, the random generator will use a fixed seed.

This means running the script again with the same parameters and Python behaviour produces the same geometry.

## 4. Generate the SVG

Save the following code as `branching.py`:

```python
from math import cos, sin, pi
from pathlib import Path
from random import Random

WIDTH = 210
HEIGHT = 297

SEED = 23
MAX_DEPTH = 8
START_LENGTH = 48.0
STROKE_WIDTH = 0.25

random = Random(SEED)
segments = []

def grow(x, y, angle, length, depth):
    if depth >= MAX_DEPTH:
        return

    x2 = x + cos(angle) * length
    y2 = y + sin(angle) * length

    segments.append((x, y, x2, y2))

    if depth + 1 == MAX_DEPTH:
        return

    spread = random.uniform(0.30, 0.48)

    left_length = length * random.uniform(
        0.68, 0.75
    )

    right_length = length * random.uniform(
        0.68, 0.75
    )

    grow(
        x2, y2,
        angle - spread,
        left_length,
        depth + 1
    )

    grow(
        x2, y2,
        angle + spread,
        right_length,
        depth + 1
    )

grow(
    105.0,
    270.0,
    -pi / 2,
    START_LENGTH,
    0
)

paths = [
    f'<path d="M {x1:.3f} {y1:.3f} '
    f'L {x2:.3f} {y2:.3f}"/>'
    for x1, y1, x2, y2 in segments
]

svg = (
    '<svg xmlns="http://www.w3.org/2000/svg" '
    f'width="{WIDTH}mm" '
    f'height="{HEIGHT}mm" '
    f'viewBox="0 0 {WIDTH} {HEIGHT}">\n'
    f'<g fill="none" stroke="#111111" '
    f'stroke-width="{STROKE_WIDTH}">\n'
    + "\n".join(paths)
    + "\n</g>\n</svg>\n"
)

Path("branching.svg").write_text(
    svg,
    encoding="utf-8"
)

print(
    f"Generated {len(paths)} paths "
    f"using seed {SEED}"
)

```

Run the script:

```bash
python branching.py

```

It creates a file named `branching.svg`.

With the provided parameters, the result contains **255 separate line paths**.

The file uses A4 dimensions in physical millimetres.

The generated geometry is represented by real SVG line segments, not by raster artwork or rendered filters.

## 5. Understand why there are 255 paths

Every segment produces two child segments until the maximum depth is reached.

The levels contain:

| Level | Segments |
| --- | --- |
| 1 | 1 |
| 2 | 2 |
| 3 | 4 |
| 4 | 8 |
| 5 | 16 |
| 6 | 32 |
| 7 | 64 |
| 8 | 128 |

The total is:

`1 + 2 + 4 + 8 + 16 + 32 + 64 + 128 = 255`

This explains why increasing the maximum depth can have a large effect on drawing complexity.

One extra level nearly doubles the number of segments.

For larger generative drawings, that increase can significantly affect path count and plotting workload.

## 6. Understand the random seed

The program uses:

```python
SEED = 23

```

This initialises Python’s random generator.

The branch angles and length variations are then generated in a repeatable sequence.

Changing the seed creates another variation.

Using the same seed with the same algorithm and settings reproduces the same mathematical choices.

That makes it possible to compare different versions without losing track of the original configuration.

However, identical SVG geometry does not guarantee identical physical ink marks.

Paper, pen condition and machine behaviour can still influence the result.

## 7. Change the branching depth

The relevant parameter is:

```python
MAX_DEPTH = 8

```

Try reducing it to 6 or 7.

The result will contain fewer segments and a simpler structure.

Increasing it produces additional detail.

But more detail is not automatically more effective.

Dense branch tips can become difficult to distinguish, especially with broader pens or small final print sizes.

Before increasing complexity, consider whether the smallest branches will remain legible on paper.

For related discussion, see [Why pen plots lose detail at smaller sizes](https://forum.plotterfolk.com/t/76).

## 8. Change the proportions

Two parameters have a particularly strong influence on appearance.

### Branch reduction

The script multiplies each branch length by a random value between 0.68 and 0.75.

Increasing this range produces longer child segments.

Decreasing it creates a more compact structure.

### Branch angle

The `spread` value controls how far each child turns from its parent.

A smaller angle creates a narrower structure.

A larger angle creates a wider and potentially more tangled pattern.

These changes also affect the physical extents of the artwork.

**If you modify the parameters, recheck the resulting SVG bounds before plotting.**

The original parameter set fits inside the specified document, but arbitrary changes may not.

## 9. Plan for the physical drawing

This algorithm creates a separate path for every branch segment.

That is useful for examining the underlying geometry.

However, the plotting software may lift the pen between segments.

The SVG does not explicitly specify machine-level pen-up and pen-down behaviour.

Some plotting software may optimise or combine movement sequences.

Other applications may execute the segments separately.

Inspect the plotting preview before sending the drawing.

Also consider whether the path order should be preserved.

The recursive structure may create different visual effects if branches are drawn in different sequences, especially when using slow-drying ink.

## 10. Consider deliberate overlaps

Branching geometry naturally creates shared endpoints.

As the structure becomes more complex, paths may also cross or overlap.

These intersections can create darker marks.

That may be desirable for some compositions.

But dense overlap can also reduce clarity.

Possible adjustments include:

- Fewer branching levels.
- A smaller angle range.
- Shorter child segments.
- A different random seed.
- A finer physical pen.
- A larger physical output format.

Changing the nominal SVG stroke width alone may not change the physical line width.

For a related explanation, see [Why changing SVG stroke width doesn’t necessarily change your plotted line](https://forum.plotterfolk.com/t/79).

## 11. Validate the generated SVG

Before plotting:

1. Open `branching.svg` in a vector editor.
2. Check the document dimensions.
3. Inspect the full composition.
4. Confirm that paths remain within the usable plotting area.
5. Review the number of paths.
6. Confirm the intended pen assignment.
7. Inspect the plotting preview.

Plotterfolk’s [SVG Preflight Checker](https://forum.plotterfolk.com/tools/svg-preflight) can help identify potential SVG compatibility issues.

The [SVG Plot Time Estimator](https://forum.plotterfolk.com/tools/svg-plot-time) can help assess the plotting workload.

Neither replaces a physical test.

## 12. Extend the system

Once the basic branching algorithm works, it can be extended in several directions.

Possible experiments include:

- Asymmetric branching.
- Different numbers of children.
- Branch lengths based on depth.
- Multiple starting points.
- Different colours assigned to selected levels.
- Deliberately constrained branching angles.
- Several branching structures in one composition.

You can also combine deterministic branching with other generative methods.

For example, compare it with the flow-field approach in [How to generate a flow field SVG for pen plotting with Python](https://forum.plotterfolk.com/t/84).

The two methods produce very different kinds of geometry.

A flow field describes paths responding to a directional field.

A branching algorithm describes a hierarchy of connected segments.

Both can produce vector artwork suitable for physical plotting when their geometry and execution requirements are properly controlled.

## The key takeaway

**Simple recursive rules can produce complex pen-plot geometry while remaining reproducible.**

A fixed random seed makes it possible to regenerate a particular variation.

Controlling the depth, angle and segment length makes the complexity manageable.

The objective is not to generate as many paths as possible.

It is to create a structure whose geometric detail, plotting workload and physical line quality support the intended composition.
