Programmatic SVG with Python

Tags: mathtechnologydesign

Some epicycloids

I created a Python module for creating SVG graphics with very few lines of code.

The advantage of vector graphics, is that they can be mathematically defined, can be easily scaled and rendered by pretty much any web browser.

The main goal was to easily plot mathematical equations and functions using svg’s <path> tag. I did this using cubic bezier paths, interpolating the functions so that their starting and ending positions and derivatives match with the bezier path.

The more points you use, the path will be more accurate, but in many cases, you don’t need more than a hundred points.

In this animation you can see 16 different epicycles, defined by:

\[P(t) = \begin{pmatrix} \left( R + \frac{R}{k} \right )\cos(t) + \frac{R}{k} \cos((k + 1)t) \\ \left( R + \frac{R}{k} \right )\sin(t) + \frac{R}{k} \sin((k + 1)t) \end{pmatrix}\]

The animation is done my calculating each svg frame, converting it to png using CairoSVG, and then piping each frame to an FFmpeg process that will generate the animation.

The advantage of using svg instead of raster graphics is that the video can be easily scaled, and each frame of the video can be exported as a high quality vector image.

You can check out the Github repository for more examples.