Creating Mathematical Animations in Python with Manim
Mathematics is a core discipline that underlies many fields like science, engineering, economics and more. Visualizing mathematical concepts through animations can greatly aid understanding and make math more engaging and approachable. In this article, we‘ll explore how to create captivating mathematical animations using Manim, a Python library built for this purpose.
What is Manim?
Manim, short for Mathematical Animation Engine, is an open-source Python library for creating explanatory math videos. It was originally created by Grant Sanderson of 3Blue1Brown to make the animations for his excellent math YouTube channel.
Using Manim, you can animate mathematical objects like shapes, graphs, equations, matrices, and more in a programmatic way. It allows fine control over positioning, timing, colors, camera angles, and other details to produce high-quality visuals. Manim renders the animations using OpenGL and outputs them as videos for easy sharing.
Installing Manim
To get started with Manim, you‘ll need Python 3.7 or higher installed. Manim also has some additional system dependencies:
- FFMPEG: for writing videos
- OpenGL: for rendering
- LaTeX (optional): for typesetting equations
The recommended way to install Manim is in a virtual environment using Poetry:
git clone https://github.com/ManimCommunity/manim.git
cd manim
poetry install
See the official installation instructions for more details based on your operating system.
Once you have Manim and its dependencies set up, you‘re ready to start animating! I recommend using Visual Studio Code or another IDE for writing your Python code.
Manim Basics: Mobjects, Animations and Scenes
There are three key concepts in Manim for creating animations:
-
Mobjects (Mathematical Objects) – Shapes, text, equations and other objects that can be displayed on screen. These are the building blocks of your animation.
-
Animations – Instructions for animating mobjects, such as movement, transformation, creation, removal, etc. Animations have a start and end time.
-
Scenes – Containers for organizing animations. A scene contains the code for your full animation sequence. You can have multiple scenes in a file.
Here‘s a simple example showcasing these concepts:
from manim import *
class SimpleAnimation(Scene):
def construct(self):
# Create a circle mobject
circle = Circle()
circle.set_fill(PINK, opacity=0.5)
# Create a square mobject
square = Square()
square.set_fill(BLUE, opacity=0.5)
# Animate the circle, then transform it to a square
self.play(Create(circle))
self.play(Transform(circle, square))
self.wait()
This defines a Scene called SimpleAnimation. The construct method is where we write our animation code. We create a pink circle, play an animation to show it on screen, then transform it into a blue square.
The set_fill method customizes the color and opacity of the mobjects. The play method is used to start animations. The wait method adds a pause at the end.
To generate a video file from this, run manim with:
manim -qm SimpleAnimation.py SimpleAnimation
This will output a MP4 video file that you can view and share!
Animating Mathematical Equations
One of the most powerful aspects of Manim is its ability to animate LaTeX equations. Manim integrates with LaTeX, the standard for academic math typesetting.
Here‘s an example of animating the quadratic formula:
class QuadraticFormula(Scene):
def construct(self):
# Create LaTeX equations
eq1 = MathTex(
"ax^2", "+", "bx", "+", "c", "=", "0"
)
eq2 = MathTex(
"x", "=", "{-b", " \\pm \\sqrt{", "b^2", "-", "4ac", "}", "\\over", "2a}"
)
# Position equations
eq1.shift(UP*2)
eq2.shift(DOWN*2)
# Play animations
self.play(Write(eq1))
self.wait()
self.play(TransformMatchingTex(eq1, eq2))
self.wait()
This creates two equation mobjects using MathTex and LaTeX syntax. The equations are positioned using the shift method.
We animate the first equation being written out with Write, wait a bit, then transform it into the second equation with TransformMatchingTex, which intelligently matches up the shared pieces.
With a few lines of code, we‘ve created a slick animation of deriving the quadratic formula! The LaTeX is automatically rendered into pretty equations.
Animating Graphs and Plotting
Manim also supports graphing and plotting mathematical functions. Here‘s an example of animating sin and cosine waves:
class SinAndCosFunctionPlot(Scene):
def construct(self):
axes = Axes(
x_range=[-PI, PI, 0.5],
y_range=[-1.5, 1.5, 0.5],
x_length=10,
axis_config={"include_numbers": True}
)
# Create sine and cosine functions
sin_graph = axes.plot(lambda x: np.sin(x), color=BLUE)
cos_graph = axes.plot(lambda x: np.cos(x), color=RED)
# Create labels
sin_label = axes.get_graph_label(
sin_graph, "\\sin(x)", x_val=-PI/2, direction=UP
)
cos_label = axes.get_graph_label(
cos_graph, label="\\cos(x)", x_val=PI/2, direction=UP
)
vert_line = axes.get_vertical_line(
axes.i2gp(TAU, cos_graph), color=GREY, line_func=Line
)
line_label = MathTex("x=2\pi")
line_label.next_to(vert_line, DOWN, buff=0.1)
plot = VGroup(axes, sin_graph, cos_graph, vert_line)
labels = VGroup(sin_label, cos_label, line_label)
self.play(DrawBorderThenFill(plot))
self.play(Write(labels))
self.wait()
self.play(
axes.animate.scale(0.6).to_corner(DL),
labels.animate.scale(0.8).shift(UR*0.5),
run_time=2
)
self.wait()
This sets up an Axes mobject with specified ranges and labels. We then use the plot function to graph the sine and cosine functions, passing in lambda functions.
Labels for the curves are created with get_graph_label and positioned relative to the curves. A vertical line is added at x=2π.
The plot, curves and labels are grouped into a single unit with VGroup. We animate them being drawn with DrawBorderThenFill and the labels being written with Write.
Finally, we animate the plot being scaled down and moved to the corner, and the labels being shifted. This shows off Manim‘s ability to seamlessly animate complex sequences.
Tips for Effective Mathematical Animations
Here are some tips for creating engaging and effective mathematical animations with Manim:
-
Keep it simple – Focus on illustrating the key concepts and avoid unnecessary clutter. Sometimes less is more.
-
Use color and highlighting effectively – Draw attention to the important parts of the animation with bright colors or flashing.
-
Go step-by-step – Break down derivations and explanations into bite-sized animated pieces for clearer communication.
-
Provide context – Don‘t assume too much knowledge on the part of the viewer. Briefly introduce key terms and symbols.
-
Add some visual flair – Little touches like rotating shapes, morphing one object into another, camera zooms/pans, can spice things up. Just don‘t overdo it!
-
Adjust timing – Make sure animations aren‘t too fast or slow. Pauses and delays in the right places help with pacing and comprehension.
-
Supplement with text and audio – On-screen labels and voice-over narration can complement the visuals to further explain what‘s being shown.
With some practice and creativity, you can use Manim to make some amazing mathematical animations! It‘s a great tool for teachers, students, researchers or anyone who wants to communicate math visually.
Resources for Learning More
To dive deeper into Manim and what it can do, check out these resources:
- 3Blue1Brown YouTube channel – The original inspiration for Manim. Amazing animated math videos!
- Manim Community Documentation – API reference and tutorials from the maintainers.
- Manim Community GitHub – Source code, issues, and discussion.
- Manim Subreddit – For sharing creations and asking questions
- Manim Discord Community – To connect with other Manim users in real-time
I hope this article has got you excited to try creating your own mathematical animations with Python and Manim! It‘s a very rewarding skill to learn. Have fun and happy animating!