Skip to content

Visualizations

panchi includes a built-in visualization system for vectors, linear transformations, and vector spaces. Two-dimensional visualizations are accessed through Animator2D, and three-dimensional ones through Animator3D — the two classes share the same six-method API, differing only in dimension. This page documents Animator2D first, then covers what changes in Animator3D.

Setup

panchi ships with a matplotlib backend by default. For higher-quality, video-based output, install the optional manim backend:

pip install panchi[manim]

Creating an animator

from panchi import Vector, Matrix, VectorSpace
from panchi.visualizations import Animator2D

# Interactive display (matplotlib pops up a window)
animator = Animator2D()

# Save to disk instead
animator = Animator2D(save_path="./my_plots")

# Use manim for video output
animator = Animator2D(backend="manim", save_path="./videos")

The backend parameter selects which rendering engine to use. Manim is only imported when you request it, so matplotlib users never need it installed.

Constructor options

Parameter Default Description
backend "matplotlib" "matplotlib" or "manim"
save_path None Directory for output files. If None, matplotlib shows interactively and manim saves to ./media.
quality "medium" Render quality: "low", "medium", "high", or "production" (manim only)
figsize (8, 8) Figure size in inches (matplotlib only)
include_extra_files False Keep manim's scratch directories next to the output (manim only)
output_format None "mp4" (the default) or "gif" (manim only)

When save_path is set, static plots are saved as .png and animations as .gif (matplotlib). The manim backend saves every method as .mp4, or as .gif with output_format="gif".


Plotting vectors

v1 = Vector([3, 2])
v2 = Vector([-1, 3])
v3 = Vector([2, -1])

animator.plot_vectors([v1, v2, v3], labels=["v1", "v2", "v3"])

Pass any number of 2D vectors as a single list. Optional parameters:

  • colors — list of hex color strings (e.g. ["#FF0000", "#0000FF"])
  • labels — list of label strings
  • grid — show coordinate grid (default True)
  • name — output filename when saving (default "plot_vectors")
Example output: three vectors as arrows from the origin
Example output.

Animating vector addition

v1 = Vector([3, 1])
v2 = Vector([1, 3])

animator.animate_addition(v1, v2)

The animation shows v1 drawn first, then v2 growing from the origin and from v1's tip simultaneously, and finally the result vector appearing. The manim backend also draws the parallelogram with dashed lines.

Optional parameters: frames, interval (milliseconds between frames), name, and colors (up to three, for [v1, v2, v1 + v2]).

Example output: two vectors added tip-to-tail
Example output.

Animating scalar multiplication

v = Vector([2, 1])

animator.animate_scaling(v, scale_factor=2.5)

The vector smoothly stretches (or shrinks, or flips for negative factors) from its original length to the scaled length.

Optional parameters: frames, interval, name, and colors (up to two, for [original, scaled]).

Example output: a vector stretching to twice its length
Example output.

Animating linear transformations

This is the signature visualization — a full grid deformation showing how a 2x2 matrix transforms the plane, in the style of 3Blue1Brown's Essence of Linear Algebra.

# 90-degree rotation
animator.animate_transform(Matrix([[0, -1], [1, 0]]))

# Horizontal shear
animator.animate_transform(Matrix([[1, 1], [0, 1]]))

# Projection onto the x-axis
animator.animate_transform(Matrix([[1, 0], [0, 0]]))

The animation shows:

  1. The standard basis vectors e1 and e2 on a coordinate grid
  2. The entire grid smoothly morphing from the identity to the target transformation
  3. Labels updating to show each vector's coordinates after the transformation

By default the standard basis is transformed. Pass vectors to watch your own vectors slide from v to matrix @ v — useful for seeing where a specific vector lands:

animator.animate_transform(
    Matrix([[2, 1], [0, 1]]),
    vectors=[Vector([1, 0]), Vector([1, 2]), Vector([-1, 1])],
)

Only 2x2 matrices are supported — a ValueError is raised for other shapes.

Optional parameters: vectors, frames, interval, name, colors (one per transformed vector, cycling if fewer are supplied), and show_matrix / show_labels.

To make the motion the whole question, hide the matrix and the coordinate labels. For example, ask "which of these has no real eigenvector?" and let students decide by watching:

animator.animate_transform(
    Matrix([[0, -1], [1, 0]]),
    vectors=[Vector([1, 0]), Vector([1, 1])],
    show_matrix=False,
    show_labels=False,
)

show_matrix hides the matrix in the corner (the matplotlib 2D backend never draws one). show_labels hides the tip labels (the 3D backends have none).

Example output: a coordinate grid shearing
Example output — a horizontal shear.

Animating row reduction

from panchi import Matrix
from panchi.algorithms import rref

reduction = rref(Matrix([[1, 2, 3], [3, 4, 5]]))
animator.animate_reduction(reduction)

Every row operation is a linear map: if E is the elementary matrix of one step, the matrix after the step has columns E @ column. animate_reduction draws the columns of the matrix as vectors and plays each step as E moving the space, with the coordinate grid deforming along with them. The deformation accumulates from step to step, a caption names the operation (for example R1 -> R1 + (-3.0) * R0), and the current matrix is shown in the corner.

When the reduction finishes, the pivot columns are drawn thicker. For an rref result they have landed on standard basis vectors; for a ref result every pivot has only zeros below it. The grid shows where the accumulated row operations send the original coordinate grid: it is the image of the standard grid under the product of every elementary matrix so far. When A is square and invertible, that product ends as A⁻¹.

The matrix needs 2 rows for Animator2D or 3 rows for Animator3D, with any number of columns, so augmented matrices [A | b] work too. Both ref and rref results are accepted. Animator3D has no grid, so it shows the column vectors together with the image of the unit cube.

Optional parameters:

  • frames — animation frames per row operation (default 40)
  • interval — milliseconds between frames (default 30)
  • colors — one color per matrix column
  • name — output filename when saving (default "animate_reduction")

Note

A row swap is a reflection, so the space flattens momentarily halfway through a swap before opening back up. Rank-deficient matrices end with their columns collapsed onto a line or a point. Both are expected.

Note

animate_reduction is currently available with the matplotlib backend only.


Visualizing spans

plot_span draws the subspace spanned by a set of vectors, with a shaded region and basis vector arrows.

# From a list of vectors
animator.plot_span([Vector([1, 2])])                      # 1D span (line)
animator.plot_span([Vector([1, 0]), Vector([0, 1])])      # 2D span (full plane)

# From a VectorSpace object
space = VectorSpace([Vector([1, 1]), Vector([1, -1])])
animator.plot_span(space, labels=["v1", "v2"])

The visualization adapts to the dimension of the subspace:

  • dim 1 — a line through the origin in the basis direction, highlighted with a colored band
  • dim 2 — the entire visible plane shaded to indicate it spans all of R²

If you pass linearly dependent vectors, panchi computes the actual basis automatically:

# These two vectors are parallel — the span is still 1D
animator.plot_span([Vector([1, 2]), Vector([2, 4])])
Example output: two vectors shading the plane they span
Example output — two independent vectors spanning R².

Comparing several spans

Pass a list of spans — each a list of vectors or a VectorSpace — to draw them together, each in its own color with a legend. This makes relationships between subspaces visible, such as two distinct lines or a plane against an axis:

animator.plot_span(
    [
        [Vector([1, 1])],              # one line
        [Vector([1, -1])],            # a different line
        VectorSpace([Vector([2, 1])]),  # a third, from a VectorSpace
    ],
    labels=["A", "B", "C"],
)

With multiple spans, colors gives one color per span and labels names them in the legend; span_color applies to the single-span case only.

Optional parameters: colors, labels, grid, name, span_color (the shade of the span region, single span only), and the options in the next section.

Showing vectors against a span

Use vectors to draw arrows on top of a span. Unlike the span's own basis arrows, they don't have to lie in it. Use gaps to join two points with a dashed line, which shows how far one is from the other:

from panchi import Matrix, Vector, qr_decomposition
from panchi.visualizations import Animator3D

X = Matrix([[1.0, 0.65], [1.0, 2.05], [1.0, 3.35]])
y = Vector([33.9, 10.4, 15.0])

q = qr_decomposition(X).q
p = q @ (q.T @ y)                   # the projection of y onto the plane

animator = Animator3D()
animator.plot_span(
    X.col_vectors,
    labels=["1", "x"],
    vectors=[y, p],
    vector_labels=["y", "p"],
    gaps=[(y, p)],
    view="edge",
)

p is the point of the plane closest to y, so the dashed gap meets the plane at a right angle. This is the picture behind least squares. Try a different p in the plane to see the gap grow and tilt.

view sets the camera for Animator3D:

  • view="edge" looks across a single plane, turned so the plane reads as the horizon and anything off the plane rises straight up.
  • view=(elevation, azimuth) or view=(elevation, azimuth, roll) sets the angles yourself, in degrees.

Optional parameters: vectors, vector_colors, vector_labels, gaps, and view. These work with both backends. In Animator2D you can use everything except view.


SVD image compression

plot_compression treats a matrix as a grayscale image and shows how well its low-rank SVD approximations reproduce it. It's a standalone function, not an Animator method, because it draws images instead of vectors:

from panchi import Matrix, svd
from panchi.visualizations import plot_compression

A = Matrix([[1 if 4 <= c <= 11 and 3 <= r <= 9 else 0 for c in range(16)]
            for r in range(16)])
result = svd(A)

plot_compression(result, [1, 3, 8])
plot_compression(result, [1, 3, 8], save_path="compression.png")

The top row shows the original next to the rank-k approximation A_k = σ₁u₁v₁ᵀ + … + σₖuₖvₖᵀ for each k, and each panel is labelled with its relative error and the share of energy it captures. The bottom panel plots both quantities for every k, so you can see where adding more singular values stops helping. Pass cmap to choose a different matplotlib colormap.


Saving output

When save_path is set, every method saves its output to that directory:

animator = Animator2D(save_path="./output")

animator.plot_vectors([Vector([1, 2])], name="my_vectors")
# → ./output/my_vectors.png

animator.animate_transform(Matrix([[0, -1], [1, 0]]), name="rotation")
# → ./output/rotation.gif  (matplotlib)
# → ./output/rotation.mp4  (manim)

The name parameter controls the filename (without extension). If omitted, it defaults to the method name (e.g. "plot_vectors", "animate_transform").

manim as GIFs

GIFs embed anywhere a video can't: READMEs, slides, LMS pages, chat. Ask manim for one with output_format:

animator = Animator2D(backend="manim", save_path="./output", output_format="gif")
clip = animator.animate_transform(Matrix([[1, 1], [0, 1]]), name="shear")
print(clip.path)  # ./output/shear.gif

Every manim method returns the saved file this way, as an object with a .path. GIFs are larger than .mp4 and limited to 256 colours, so faint details such as grid lines come out a little dimmer.


Backend comparison

Feature matplotlib manim
Install Included with panchi pip install panchi[manim] + system deps
Output format .png / .gif .mp4 or .gif (output_format)
Interactive display Yes (plt.show()) No (always renders to file)
Plays inline in Jupyter Yes Yes (the saved file is embedded)
Grid morph quality Good (LineCollection interpolation) Excellent (native NumberPlane)
LaTeX labels No Yes
Parallelogram in addition 3D only Yes
Render speed Fast Slower (video encoding)

Both backends support plot_vectors, animate_addition, animate_scaling, animate_transform and plot_span with the same API, for both Animator2D and Animator3D. animate_reduction is currently matplotlib-only.


3D visualizations (Animator3D)

Animator3D mirrors Animator2D for vectors in R³. It exposes the same six methods — plot_vectors, animate_addition, animate_scaling, animate_transform, plot_span, and animate_reduction — with identical signatures. Everything above about backends, save_path, output formats, and the name parameter applies unchanged; only the geometry becomes three-dimensional.

from panchi import Vector, Matrix, VectorSpace
from panchi.visualizations import Animator3D

animator = Animator3D()                          # interactive matplotlib
animator = Animator3D(save_path="./output")      # save .png / .gif
animator = Animator3D(backend="manim", save_path="./videos")

The constructor takes the same parameters as Animator2D.

All vectors passed to Animator3D must be 3D; a 2D vector raises a ValueError.

Plotting vectors

animator.plot_vectors(
    [Vector([3, 2, 1]), Vector([-1, 2, 3]), Vector([1, -2, 2])],
    labels=["v1", "v2", "v3"],
)

Each vector is drawn as a 3D arrow from the origin inside an x/y/z coordinate box. Accepts the same colors, labels, grid, and name options as the 2D version.

Example output: three vectors as arrows from the origin in 3D
Example output.

Animating vector addition

animator.animate_addition(Vector([3, 1, 0]), Vector([1, 2, 3]))

Draws v1, then v2 growing tip-to-tail from v1, and finally the result — with the parallelogram spanned by v1 and v2 shown as a translucent face. Same frames, interval, name, and colors ([v1, v2, v1 + v2]) options as in 2D.

Example output: two 3D vectors added tip-to-tail
Example output.

Animating scalar multiplication

animator.animate_scaling(Vector([2, 1, 1]), scale_factor=2.0)

The vector stretches, shrinks, or flips in R³ exactly as in the 2D case. Options: frames, interval, name, and colors ([original, scaled]).

Example output: a 3D vector stretching to twice its length
Example output.

Animating linear transformations

# rotate 45° about the z-axis
animator.animate_transform(Matrix([[1, -1, 0], [1, 1, 0], [0, 0, 1]]))

The 3D analogue: each vector slides from v to matrix @ v, with the matrix shown as an overlay. By default the three standard basis vectors are transformed (their images are the columns of the matrix). Pass vectors to transform your own instead:

animator.animate_transform(
    Matrix([[2, 0, 0], [0, 1, 0], [0, 1, 1]]),
    vectors=[Vector([1, 1, 0]), Vector([0, 1, 2])],
)

Only 3x3 matrices are supported — a ValueError is raised for other shapes. Options: vectors, frames, interval, name, colors (one per transformed vector, cycling if fewer are supplied), and show_matrix. show_labels is accepted too, but has no effect because 3D tips are never labelled.

Example output: the unit cube morphing under a 3x3 matrix
Example output — a rotation about the z-axis.

Visualizing spans

animator.plot_span([Vector([1, 0, 1]), Vector([0, 1, 1])], labels=["v1", "v2"])

plot_span adapts to the dimension of the subspace:

  • dim 1 — a line through the origin in the basis direction
  • dim 2 — a shaded plane patch through the origin
  • dim 3 — a translucent cube indicating the span fills all of R³

As in 2D, linearly dependent vectors are reduced to the true basis automatically, so the drawn dimension reflects the real span. You can also pass a list of spans to compare several subspaces at once — each drawn in its own color with a legend (e.g. a plane against an axis):

animator.plot_span(
    [
        [Vector([1, 0, 0]), Vector([0, 1, 0])],  # the xy-plane
        VectorSpace([Vector([0, 0, 1])]),         # the z-axis
    ],
    labels=["plane", "axis"],
)

Options: colors, labels, grid, name, span_color, and the vectors, vector_colors, vector_labels, gaps, and view options from Showing vectors against a span.

Example output: two 3D vectors shading the plane they span
Example output — two independent vectors spanning a plane in R³.

Animating row reduction

from panchi import Matrix
from panchi.algorithms import rref

animator.animate_reduction(rref(Matrix([[1, 2, 3], [2, 5, 7], [0, 1, 2]])))

The matrix needs 3 rows, with any number of columns. The columns are drawn as 3D arrows together with the image of the unit cube, which shows how each row operation deforms space. Captions, the on-screen matrix, and the thick pivot columns at the end work as in 2D. A ValueError is raised for any other number of rows.