How to generate a flow field SVG for pen plotting with Python

Flow fields are a popular technique in generative art. They can produce organic-looking curves, flowing compositions and complex patterns from relatively simple mathematical rules.

But creating a flow field for a screen is not quite the same as creating one for a pen plotter.

A pen plotter needs actual vector trajectories. Every line has to be physically drawn, and decisions about spacing, path length and drawing size directly affect the finished work.

In this tutorial, we’ll build a simple flow field using Python’s standard library, export it as an SVG and examine the parameters that matter when preparing it for physical pen plotting.

No external Python packages are required.

1. What is a flow field?

A flow field assigns a direction to each position in a two-dimensional space.

Imagine placing a small arrow at every point on a sheet of paper. Each arrow indicates which direction a moving particle should follow.

If you start a particle at one position and repeatedly move it in the direction indicated by the field, it traces a path.

Repeat that process from many starting positions, and the result is a collection of flowing lines.

The appearance depends on several factors:

  • How the direction field is calculated.
  • Where the starting points are placed.
  • How far each particle moves at every step.
  • How many steps are calculated.
  • Where trajectories are stopped.
  • How many trajectories are generated.

The important thing for pen plotting is that these movements can be saved as real SVG paths, rather than rendered as pixels.

2. Start with physical dimensions

Before generating any geometry, decide how large the finished drawing should be.

For this example, we’ll use an A4 document:

  • Width: 210 mm.
  • Height: 297 mm.
  • Internal margin: 15 mm.

These dimensions will be written directly into the SVG.

That matters because an SVG can have a valid coordinate system without clearly specifying its intended physical size.

For pen plotting, we want the relationship between coordinates and millimetres to be explicit.

Our example will use the following SVG structure:

<svg xmlns="http://www.w3.org/2000/svg"
     width="210mm"
     height="297mm"
     viewBox="0 0 210 297">
</svg>

With this configuration, one unit in the SVG coordinate system corresponds to one millimetre in the declared document dimensions.

The actual usable area may still depend on your plotter and its paper-holding system.

3. Create the flow field in Python

The following script generates a complete SVG using only Python’s standard library.

Save it as flow_field.py.

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

WIDTH, HEIGHT = 210, 297  # A4, millimetres
MARGIN = 15
SEED = 7
STEP_MM = 1.5
MAX_STEPS = 85

rng = Random(SEED)
phase_x = rng.uniform(-pi, pi)
phase_y = rng.uniform(-pi, pi)

def heading(x, y):
    return (
        0.75 * sin(x / 35 + phase_x)
        + 0.55 * cos(y / 45 + phase_y)
    )

paths = []

for row in range(12):
    for col in range(7):
        x = 22 + col * 17
        y = 22 + row * 21

        points = [(x, y)]

        for _ in range(MAX_STEPS):
            angle = heading(x, y)

            nx = x + STEP_MM * cos(angle)
            ny = y + STEP_MM * sin(angle)

            if not (
                MARGIN <= nx <= WIDTH - MARGIN
                and MARGIN <= ny <= HEIGHT - MARGIN
            ):
                break

            x, y = nx, ny
            points.append((x, y))

        if len(points) < 8:
            continue

        commands = [
            f"M {points[0][0]:.2f} {points[0][1]:.2f}"
        ]

        commands += [
            f"L {px:.2f} {py:.2f}"
            for px, py in points[1:]
        ]

        paths.append(
            '  <path d="' + ' '.join(commands) + '" />'
        )

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

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

print(f"Generated {len(paths)} paths")

Run the script from a terminal:

python flow_field.py

It creates a file named flow-field.svg in the current directory.

With the parameters shown, the script generates 84 paths.

You can open the result in Inkscape, another SVG editor or compatible plotting software.

The output contains actual polylines, not a raster image.

4. Understand how the algorithm works

The script has three main components.

The direction field

The heading(x, y) function calculates a direction angle for any position.

It combines two trigonometric functions:

0.75 * sin(x / 35 + phase_x)
+ 0.55 * cos(y / 45 + phase_y)

The result changes gradually as the coordinates change, creating a smooth directional field.

The values are creative parameters rather than physical measurements.

Changing the coefficients or divisors alters the curvature and overall structure of the generated lines.

The starting points

The nested loops define the initial positions:

for row in range(12):
    for col in range(7):

This creates a regular arrangement of 84 starting points.

Each starting point produces a separate trajectory, provided that enough valid steps can be calculated.

Using a regular grid makes the result easier to understand, but other arrangements are possible.

For example, starting points could follow a circle, occupy a selected region or be distributed using a seeded random generator.

The integration steps

Each trajectory advances using:

nx = x + STEP_MM * cos(angle)
ny = y + STEP_MM * sin(angle)

This is a simple forward-Euler integration method.

At each step, the algorithm calculates the current direction and moves a small distance along it.

Repeating this operation constructs a sequence of points.

Those points become an SVG path using M and L commands.

This is a deliberately simple implementation. More advanced numerical integration methods can provide greater accuracy, particularly when the direction changes rapidly.

For an introductory pen-plotting example, the basic method is enough to demonstrate the process.

5. Control the geometry before plotting

A flow field can become unnecessarily complex if its parameters are not chosen carefully.

Several settings deserve particular attention.

Number of trajectories

More starting points usually means more paths.

This can increase visual density, plotting time and the risk of overlapping ink.

Try reducing the number of rows or columns before increasing the complexity of the field itself.

A composition with fewer well-positioned trajectories may work better physically than a much denser version.

Step length

The parameter STEP_MM controls the distance between successive calculated points.

In our example:

STEP_MM = 1.5

Smaller steps produce more points along a trajectory.

That can improve the approximation of curved movement, but it also increases the number of segments and the size of the SVG.

Larger steps reduce the amount of geometry, but tight curves may begin to look visibly angular.

The appropriate value depends on the curvature of the field and the intended drawing size.

This parameter is a geometric integration step, not the physical movement speed of the plotter.

Maximum steps

The parameter MAX_STEPS limits the number of movements calculated for each trajectory.

Longer paths can create more developed curves, but they may also increase line overlap and total drawing distance.

A useful approach is to begin with a relatively small value, inspect the composition and increase it only when the additional geometry contributes something meaningful.

Boundaries

The script stops trajectories when their next calculated point would leave the defined internal margin.

This prevents the generated path coordinates from extending outside the chosen drawing region.

However, it does not automatically verify the plotter’s mechanical travel limits, pen-holder clearances or the physical width of the ink mark.

Those remain separate considerations.

6. Make the result reproducible

Generative artwork often involves random variation.

If you want to reproduce a composition, record the parameters used to create it.

Our example includes:

SEED = 7

Python’s seeded random generator determines two phase values used by the directional field.

Using the same seed and the same other parameters produces the same numerical construction in the same compatible environment.

Changing the seed changes the field and therefore the resulting composition.

This makes it possible to create several related variations without manually redrawing the geometry.

For a finished artwork, preserve the actual exported SVG as well as the source code and parameters.

That way, the physical drawing does not depend on rerunning a potentially modified generator.

The distinction between exploring variations and freezing the selected geometry is also discussed in Freezing randomness before the plotter.

7. Check whether the geometry is suitable for a real pen

A valid SVG is not automatically a successful pen plot.

Our example generates continuous paths made from straight segments, but several physical considerations remain.

Line spacing

Some trajectories may converge or overlap.

A fine pen may preserve separation in areas where a broader pen produces a darker combined mark.

Stroke appearance

The SVG uses a nominal stroke-width of 0.25.

This controls the rendered appearance. It does not guarantee that the physical line will measure 0.25 mm.

Plotting duration

The total drawing distance, number of paths, travel movements and pen lifts all affect execution time.

Ink accumulation

Repeated or overlapping trajectories may deposit more ink in particular regions.

Path order

The exported paths are written in the order they were generated.

Your plotting software may preserve or modify that order.

Before producing the complete artwork, inspect the result at its intended physical size.

For a broader discussion of designing generative geometry for physical output, see Designing generative art for physical pen plotting.

8. Use Plotterfolk’s tools to inspect the SVG

After generating flow-field.svg, three existing Plotterfolk tools can help with preparation.

SVG Preflight Checker

Open SVG Preflight Checker

Use it to inspect the SVG’s declared dimensions, stroke properties and potential compatibility concerns.

The checker identifies issues worth reviewing but does not automatically repair the file or guarantee compatibility with every plotter.

SVG Plot Time Estimator

Open SVG Plot Time Estimator

Use it to examine drawing distance, travel distance, path-related measurements and estimated plotting duration.

The result depends on the physical speeds and additional machine settings entered.

It is a planning estimate, not an exact prediction of execution time.

SVG Plotter Optimizer

Open SVG Plotter Optimizer

Use it to investigate whether unnecessary travel can be reduced.

For an initial comparison, prefer a travel-only approach that preserves the original linework.

More aggressive operations may simplify geometry, join trajectories or remove selected paths.

Those changes can affect the composition or introduce additional ink.

Always compare the optimized result with the original before exporting.

9. Experiment with controlled variations

Once the basic generator works, try changing one parameter at a time.

For example:

Variation Change What to examine
A Reduce starting points Line density and open space
B Reduce step length Curve approximation and segment count
C Increase maximum steps Path development and overlap
D Change the random seed Overall composition
E Change field coefficients Curvature and directional structure

Keep the original SVG for comparison.

It can also be useful to compare plotting-time estimates before deciding which variation to produce physically.

Do not assume that the most complex result is the most interesting one.

Generative pen plotting offers a useful constraint: every additional path should justify the movement, time and physical mark it creates.

10. What this example does not attempt to solve

This introductory generator deliberately avoids several more advanced problems.

It does not:

  • Enforce minimum spacing between neighbouring trajectories.
  • Detect or eliminate every overlapping segment.
  • Optimize path order.
  • Simulate actual ink deposition.
  • Support automatic multi-pen assignments.
  • Guarantee smooth physical movement on every plotter.
  • Account for machine acceleration or mechanical behaviour.

These could be added in a more advanced implementation.

However, adding every possible feature would make the basic principle harder to understand.

The purpose of this example is to show the complete process from a mathematical direction field to a physical-size SVG containing drawable vector paths.

The key takeaway

A flow field becomes useful for pen plotting when its mathematical output is translated into deliberate, physically manageable trajectories.

The essential process is straightforward:

  1. Define a directional field.
  2. Choose starting positions.
  3. Integrate trajectories through the field.
  4. Stop paths within the intended drawing area.
  5. Export real SVG geometry with physical dimensions.
  6. Inspect and prepare the result before plotting.

Once this workflow is understood, the same principles can be extended to more complex generative systems.

The goal is not to generate the maximum possible number of lines.

It is to generate geometry that makes sense both as a digital composition and as a physical drawing.

If you experiment with the script, consider sharing the seed, relevant parameters, SVG preview and — when available — a photograph of the plotted result.

Comparing the digital geometry with its physical output can be a useful way to understand how generative systems behave on paper.