#!/usr/bin/env python # coding: utf-8 # # Welcome to Manim! # This is a temporary test environment in which you can play around with Manim without the need of installing it locally. Some basic knowledge of Python is helpful! Keep in mind that this is a *temporary* environment, though: your changes will not be saved and cannot be shared with others. To save your work, you will need to download the notebook file ("File > Download as > Notebook (.ipynb)"). Enjoy! # # > *Useful resources:* [Documentation](https://docs.manim.community), [Discord](https://discord.gg/mMRrZQW), [Reddit](https://www.reddit.com/r/manim/) # ## Setup # We begin our short walkthrough by importing everything from the library. Run the following code cell to do so (focus the cell and hit the *Run* button above, or press `Shift`+`Enter` – you can find more information about how to navigate and work with Jupyter notebooks in the *Help* menu at the top of this page). # # The second line controls the maximum width used to display videos in this notebook, and the third line controls the verbosity of the log output. Feel free to adapt both of these settings to your liking. # In[ ]: from manim import * config.media_width = "75%" config.verbosity = "WARNING" # If you have executed the cell successfully, a message printing the installed version of the library should have appeared below it. # ## Your first Scene # Manim generates videos by rendering *Scenes*. These are special classes that have a `construct` method describing the animations that should be rendered. (For the sake of this tutorial it doesn't matter if you are not that familiar with Python or object-oriented programming terminology like *class* or *method* – but you should consider working through a Python tutorial if you want to keep learning Manim.) # # Enough of fancy words, let us look at an example. Run the cell below to render and display a video. # In[ ]: get_ipython().run_cell_magic('manim', '-qm CircleToSquare', '\nclass CircleToSquare(Scene):\n def construct(self):\n blue_circle = Circle(color=BLUE, fill_opacity=0.5)\n green_square = Square(color=GREEN, fill_opacity=0.8)\n self.play(Create(blue_circle))\n self.wait()\n \n self.play(Transform(blue_circle, green_square))\n self.wait()\n') # While parts of this example might seem self-explanatory, we'll still go over it step by step. First, # ``` # %%manim -qm CircleToSquare # ``` # is a *magic command*, it only works within Jupyter notebooks. It is very similar to how you would call `manim` from a terminal: The flag `-qm` controls the render quality, it is shorthand for `--quality=m`, medium rendering quality. This means that the video will be rendered in 720p with 30 fps. (Try to change it to `-qh` or `-ql` for *high* and *low* quality, respectively!) # # Finally, `CircleToSquare` is the name of the scene class you want to render in this particular cell, which already brings us to the next few lines: # ```py # class CircleToSquare(Scene): # def construct(self): # [...] # ``` # This defines a Manim scene named `CircleToSquare`, and defines a custom `construct` method which acts as the *blueprint* for the video. The content of the `construct` method describes what exactly is rendered in the video. # ```py # blue_circle = Circle(color=BLUE, fill_opacity=0.5) # green_square = Square(color=GREEN, fill_opacity=0.8) # ``` # The first two lines create a `Circle` and a `Square` object with the specified colors and fill opacities. However, these are not added to the scene yet! To do that, you either have to use `self.add`, or ... # ```py # self.play(Create(blue_circle)) # self.wait() # ``` # ... by playing an animation that adds a Manim object (*Mobject*) to the scene. Within the method, `self` references the current scene, `self.play(my_animation)` can be read as "*This scene should play my animation.*" # # `Create` is such an animation, but there are many others (for example `FadeIn`, or `DrawBorderThenFill` – try them out above!). The `self.wait()` call does exactly what you would expect: it pauses the video for a while (by default: one second). Change it to `self.wait(2)` for a two-second pause, and so on. # # The final two lines, # ``` # self.play(Transform(blue_circle, green_square)) # self.wait() # ``` # are responsible for the actual transformation from the blue circle to the green square (plus a one second pause afterwards). # ## Positioning Mobjects and moving them around # New problem: We want to create a scene in which a circle is created while simultaneously some text is written below it. We can reuse our blue circle from above, and then add some new code: # In[ ]: get_ipython().run_cell_magic('manim', '-qm HelloCircle', '\nclass HelloCircle(Scene):\n def construct(self):\n # blue_circle = Circle(color=BLUE, fill_opacity=0.5)\n # We can also create a "plain" circle and add the desired attributes via set methods:\n circle = Circle()\n blue_circle = circle.set_color(BLUE).set_opacity(0.5)\n \n label = Text("A wild circle appears!")\n label.next_to(blue_circle, DOWN, buff=0.5)\n \n self.play(Create(blue_circle), Write(label))\n self.wait()\n') # Apparently, text can be rendered by using a `Text` Mobject – and the desired position is achieved by the line # ```py # label.next_to(blue_circle, DOWN, buff=0.5) # ``` # Mobjects have a few methods for positioning, `next_to` is one of them (`shift`, `to_edge`, `to_corner`, `move_to` are a few others – check them out in our [documentation](https://docs.manim.community/) by using the search bar on the left!). For `next_to`, the first argument that is passed (`blue_circle`) describes next to which object our `label` should be placed. The second argument, `DOWN`, describes the direction (try changing it to `LEFT`, `UP`, or `RIGHT` instead!). And finally, `buff=0.5` controls the "buffer distance" between `blue_circle` and `label`, increasing this value will push `label` further down. # # But also note that the `self.play` call has been changed: it is possible to pass several animation arguments to `self.play`, they will then be played simultaneously. If you want to play them one after the other, replace the `self.play` call with the lines # ```py # self.play(Create(blue_circle)) # self.play(Write(label)) # ``` # and see what happens. # # By the way, Mobjects naturally also have non-positioning related methods: for example, to get our blue circle, we could also create a default one, and then set color and opacity: # ```py # circle = Circle() # blue_transparent_circle = circle.set_color(BLUE) # blue_circle = blue_transparent_circle.set_opacity(0.5) # ``` # A shorter version of this would be # ```py # blue_circle = Circle().set_color(BLUE).set_opacity(0.5) # ``` # For now, we will stick with setting the attributes directly in the call to `Circle`. # ## Animating Method calls: the `.animate` syntax # In the last example we have encountered the `.next_to` method, one of many (!) methods that modify Mobjects in one way or the other. But what if we wanted to animate how a Mobject changes when one of these methods is applied, say, when we `.shift` something around, or `.rotate` a Mobject, or maybe `.scale` it? The `.animate` syntax is the answer to this question, let us look at an example. # In[ ]: get_ipython().run_cell_magic('manim', '-qm CircleAnnouncement', '\nclass CircleAnnouncement(Scene):\n def construct(self):\n blue_circle = Circle(color=BLUE, fill_opacity=0.5)\n announcement = Text("Let us draw a circle.")\n \n self.play(Write(announcement))\n self.wait()\n \n self.play(announcement.animate.next_to(blue_circle, UP, buff=0.5))\n self.play(Create(blue_circle))\n') # Where we would normally use `announcement.next_to(blue_circle, UP, buff=0.5)` to position the text without animation, we can prepend `.animate` to the method call to turn the application of the method into an animation which can then be played using `self.play`. This works with all methods that modify a Mobject in some way: # In[ ]: get_ipython().run_cell_magic('manim', '-qm AnimateSyntax', '\nclass AnimateSyntax(Scene):\n def construct(self):\n triangle = Triangle(color=RED, fill_opacity=1)\n self.play(DrawBorderThenFill(triangle))\n self.play(triangle.animate.shift(LEFT))\n self.play(triangle.animate.shift(RIGHT).scale(2))\n self.play(triangle.animate.rotate(PI/3))\n') # In the first play call the triangle is created, in the second it is shifted to the left, then in the third it is shifted back to the right and simultaneously scaled by a factor of 2, and finally in the fourth call it is rotated by an angle of $\pi/3$. Run the cell above again after modifying some of the values, or trying other methods like, e.g., `set_color`). # When looking closely at the last animation from the scene above, the rotation, you might notice that this is not *actually* a rotation. The triangle is transformed to a rotated version of itself, but during the animation the vertices of the triangle don't move along an arc (as they would when the triangle was rotated around its center), but rather along straight lines, which gives the animation the impression that the triangle first shrinks a bit and then grows again. # # This is actually **not a bug**, but a consequence of how the `.animate` syntax works: the animation is constructed by specifying the starting state (the `triangle` Mobject in the example above), and the final state (the rotated mobject, `triangle.rotate(PI/3)`). Manim then tries to interpolate between these two, but doesn't actually know that you would like to smoothly rotate the triangle. The following example illustrates this clearly: # In[ ]: get_ipython().run_cell_magic('manim', '-qm DifferentRotations', '\nclass DifferentRotations(Scene):\n def construct(self):\n left_square = Square(color=BLUE, fill_opacity=0.7).shift(2*LEFT)\n right_square = Square(color=GREEN, fill_opacity=0.7).shift(2*RIGHT)\n self.play(left_square.animate.rotate(PI), Rotate(right_square, angle=PI), run_time=2)\n self.wait()\n') # ## Typesetting Mathematics # Manim supports rendering and animating LaTeX, the markup language mathematics is very often typeset in. Learn more about it [in this 30 minute tutorial](https://www.overleaf.com/learn/latex/Learn_LaTeX_in_30_minutes). # # Here is a simple example for working with LaTeX in Manim: # In[ ]: get_ipython().run_cell_magic('manim', '-qm CauchyIntegralFormula', '\nclass CauchyIntegralFormula(Scene):\n def construct(self):\n formula = MathTex(r"[z^n]f(z) = \\frac{1}{2\\pi i}\\oint_{\\gamma} \\frac{f(z)}{z^{n+1}}~dz")\n self.play(Write(formula), run_time=3)\n self.wait()\n') # As this example demonstrates, `MathTex` allows to render simple (math mode) LaTeX strings. If you want to render "normal mode" LaTex, use `Tex` instead. # # Of course, Manim can also help you to visualize transformations of typeset formulae. Consider the following example: # In[ ]: get_ipython().run_cell_magic('manim', '-qm TransformEquation', '\nclass TransformEquation(Scene):\n def construct(self):\n eq1 = MathTex("42 {{ a^2 }} + {{ b^2 }} = {{ c^2 }}")\n eq2 = MathTex("42 {{ a^2 }} = {{ c^2 }} - {{ b^2 }}")\n eq3 = MathTex(r"a^2 = \\frac{c^2 - b^2}{42}")\n self.add(eq1)\n self.wait()\n self.play(TransformMatchingTex(eq1, eq2))\n self.wait()\n self.play(TransformMatchingShapes(eq2, eq3))\n self.wait()\n') # In this last example, `eq1` and `eq2` have some double braces positions where, conventionally, there wouldn't be any in plain LaTeX. This is special Manim notation that groups the resulting `Tex` Mobjects `eq1` and `eq2` in a particular way. # # This special notation is helpful when using the `TransformMatchingTex` animation: it will transform parts with equal TeX strings (for example, `a^2` to `a^2`) into each other – and without the special notation, the equation is considered to be one long TeX string. In comparison, `TransformMatchingShapes` is less smart: it simply tries to transform shapes that "look the same" into each other – nonetheless, it is still often very useful. # If you have made it this far, you should have a first impression of basic usage of the library. You can find a few more advanced examples that illustrate some more specialized concepts in the library below. Go ahead, try to play around and modify them just like you did for the ones above! Explore our [documentation](https://docs.manim.community) to get an idea about things that are already implemented – and look at the source code in case you want to build some more complex objects yourself. # # The [community](https://www.manim.community/discord/) is certainly also happy to answer questions – and we hope you share your awesome projects with us! **Happy *manimating*!** # ## Some more specialized examples # Before you delve right into these examples: please note that they illustrate specialized concepts, they are meant to give you a feeling for how more complex scenes are setup and coded. The examples don't come with additional explanation, they are **not intended as (entry level) learning resources**. # In[ ]: get_ipython().run_cell_magic('manim', '-qm FormulaEmphasis', '\nclass FormulaEmphasis(Scene):\n def construct(self):\n product_formula = MathTex(\n r"\\frac{d}{dx} f(x)g(x) =",\n r"f(x) \\frac{d}{dx} g(x)",\n r"+",\n r"g(x) \\frac{d}{dx} f(x)"\n )\n self.play(Write(product_formula))\n box1 = SurroundingRectangle(product_formula[1], buff=0.1)\n box2 = SurroundingRectangle(product_formula[3], buff=0.1)\n self.play(Create(box1))\n self.wait()\n self.play(Transform(box1, box2))\n self.wait()\n') # In[ ]: get_ipython().run_cell_magic('manim', '-qm PlotExample', '\nclass PlotExample(Scene):\n def construct(self):\n plot_axes = Axes(\n x_range=[0, 1, 0.05],\n y_range=[0, 1, 0.05],\n x_length=9,\n y_length=5.5,\n axis_config={\n "numbers_to_include": np.arange(0, 1 + 0.1, 0.1),\n "font_size": 24,\n },\n tips=False,\n )\n\n y_label = plot_axes.get_y_axis_label("y", edge=LEFT, direction=LEFT, buff=0.4)\n x_label = plot_axes.get_x_axis_label("x")\n plot_labels = VGroup(x_label, y_label)\n\n plots = VGroup()\n for n in np.arange(1, 20 + 0.5, 0.5):\n plots += plot_axes.plot(lambda x: x**n, color=WHITE)\n plots += plot_axes.plot(\n lambda x: x**(1 / n), color=WHITE, use_smoothing=False\n )\n\n extras = VGroup()\n extras += plot_axes.get_horizontal_line(plot_axes.c2p(1, 1, 0), color=BLUE)\n extras += plot_axes.get_vertical_line(plot_axes.c2p(1, 1, 0), color=BLUE)\n extras += Dot(point=plot_axes.c2p(1, 1, 0), color=YELLOW)\n title = Title(\n r"Graphs of $y=x^{\\frac{1}{n}}$ and $y=x^n (n=1, 1.5, 2, 2.5, 3, \\dots, 20)$",\n include_underline=False,\n font_size=40,\n )\n \n self.play(Write(title))\n self.play(Create(plot_axes), Create(plot_labels), Create(extras))\n self.play(AnimationGroup(*[Create(plot) for plot in plots], lag_ratio=0.05))\n') # In[ ]: get_ipython().run_cell_magic('manim', '-qm ErdosRenyiGraph', '\nimport networkx as nx\n\nnxgraph = nx.erdos_renyi_graph(14, 0.5)\n\nclass ErdosRenyiGraph(Scene):\n def construct(self):\n G = Graph.from_networkx(nxgraph, layout="spring", layout_scale=3.5)\n self.play(Create(G))\n self.play(*[G[v].animate.move_to(5*RIGHT*np.cos(ind/7 * PI) +\n 3*UP*np.sin(ind/7 * PI))\n for ind, v in enumerate(G.vertices)])\n self.play(Uncreate(G))\n') # In[ ]: get_ipython().run_cell_magic('manim', '-qm CodeFromString', '\nclass CodeFromString(Scene):\n def construct(self):\n code = \'\'\'from manim import Scene, Square\n\nclass FadeInSquare(Scene):\n def construct(self):\n s = Square()\n self.play(FadeIn(s))\n self.play(s.animate.scale(2))\n self.wait()\n\'\'\'\n rendered_code = Code(code=code, tab_width=4, background="window",\n language="Python", font="Monospace")\n self.play(Write(rendered_code))\n self.wait(2)\n') # In[ ]: get_ipython().run_cell_magic('manim', '-qm OpeningManim', '\nclass OpeningManim(Scene):\n def construct(self):\n title = Tex(r"This is some \\LaTeX")\n basel = MathTex(r"\\sum_{n=1}^\\infty \\frac{1}{n^2} = \\frac{\\pi^2}{6}")\n VGroup(title, basel).arrange(DOWN)\n self.play(\n Write(title),\n FadeIn(basel, shift=UP),\n )\n self.wait()\n\n transform_title = Tex("That was a transform")\n transform_title.to_corner(UP + LEFT)\n self.play(\n Transform(title, transform_title),\n LaggedStart(*[FadeOut(obj, shift=DOWN) for obj in basel]),\n )\n self.wait()\n\n grid = NumberPlane(x_range=(-10, 10, 1), y_range=(-6.0, 6.0, 1))\n grid_title = Tex("This is a grid")\n grid_title.scale(1.5)\n grid_title.move_to(transform_title)\n\n self.add(grid, grid_title)\n self.play(\n FadeOut(title),\n FadeIn(grid_title, shift=DOWN),\n Create(grid, run_time=3, lag_ratio=0.1),\n )\n self.wait()\n\n grid_transform_title = Tex(\n r"That was a non-linear function \\\\ applied to the grid"\n )\n grid_transform_title.move_to(grid_title, UL)\n grid.prepare_for_nonlinear_transform()\n self.play(\n grid.animate.apply_function(\n lambda p: p + np.array([np.sin(p[1]), np.sin(p[0]), 0])\n ),\n run_time=3,\n )\n self.wait()\n self.play(Transform(grid_title, grid_transform_title))\n self.wait()\n') # In[ ]: