API 参考:Mobject 核心

共 21 个类,按字母排序。每个类含中文说明、继承链、参数表与上手示例,API 文档由 autodoc 从 manim v0.21.0 源码自动生成;带完整中文精讲的类见 API 索引。

ArrowVectorField

把向量场画成带箭头的网格:每个采样点一支方向箭头,随场强缩放,是微分方程可视化的主力。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Mobject" -> "VMobject"; "VMobject" -> "VGroup"; "VGroup" -> "VectorField"; "VectorField" -> "ArrowVectorField"; }

参数

func

—

color

None

color_scheme

None

min_color_scheme_value

0,float

max_color_scheme_value

2,float

colors

[ManimColor('#236B8E'), Man…

x_range

None,Sequence[float]

y_range

None,Sequence[float]

z_range

None,Sequence[float]

three_dimensions

False,bool

length_func

<function ArrowVectorField.…,Callable[[float], float]

opacity

1.0,float

vector_config

None,dict | None

快速上手

field = ArrowVectorField(lambda p: np.array([-p[1], p[0], 0]))
self.add(field)

API 文档

class manim.ArrowVectorField(func: ~collections.abc.Callable[[~numpy.ndarray], ~numpy.ndarray], color: ~manim.utils.color.core.ManimColor | int | str | ~numpy._typing._array_like.NDArray[~numpy.int64] | tuple[int, int, int] | ~numpy._typing._array_like.NDArray[~numpy.float64] | tuple[float, float, float] | tuple[int, int, int, int] | tuple[float, float, float, float] | None = None, color_scheme: ~collections.abc.Callable[[~numpy.ndarray], float] | None = None, min_color_scheme_value: float = 0, max_color_scheme_value: float = 2, colors: ~collections.abc.Sequence[~manim.utils.color.core.ManimColor | int | str | ~numpy._typing._array_like.NDArray[~numpy.int64] | tuple[int, int, int] | ~numpy._typing._array_like.NDArray[~numpy.float64] | tuple[float, float, float] | tuple[int, int, int, int] | tuple[float, float, float, float]] = [ManimColor('#236B8E'), ManimColor('#83C167'), ManimColor('#F7D96F'), ManimColor('#FC6255')], x_range: ~collections.abc.Sequence[float] = None, y_range: ~collections.abc.Sequence[float] = None, z_range: ~collections.abc.Sequence[float] = None, three_dimensions: bool = False, length_func: ~collections.abc.Callable[[float], float] = <function ArrowVectorField.<lambda>>, opacity: float = 1.0, vector_config: dict | None = None, **kwargs)

基类:VectorField

A VectorField represented by a set of change vectors.

Vector fields are always based on a function defining the Vector at every position. The values of this functions is displayed as a grid of vectors. By default the color of each vector is determined by it's magnitude. Other color schemes can be used however.

Parameters

func

The function defining the rate of change at every position of the vector field.

color

The color of the vector field. If set, position-specific coloring is disabled.

color_scheme

A function mapping a vector to a single value. This value gives the position in the color gradient defined using min_color_scheme_value, max_color_scheme_value and colors.

min_color_scheme_value

The value of the color_scheme function to be mapped to the first color in colors. Lower values also result in the first color of the gradient.

max_color_scheme_value

The value of the color_scheme function to be mapped to the last color in colors. Higher values also result in the last color of the gradient.

colors

The colors defining the color gradient of the vector field.

x_range

A sequence of x_min, x_max, delta_x

y_range

A sequence of y_min, y_max, delta_y

z_range

A sequence of z_min, z_max, delta_z

three_dimensions

Enables three_dimensions. Default set to False, automatically turns True if z_range is not None.

length_func

The function determining the displayed size of the vectors. The actual size of the vector is passed, the returned value will be used as display size for the vector. By default this is used to cap the displayed size of vectors to reduce the clutter.

opacity

The opacity of the arrows.

vector_config

Additional arguments to be passed to the Vector constructor

kwargs

Additional arguments to be passed to the VGroup constructor

Examples

class BasicUsage(Scene):
    def construct(self):
        func = lambda pos: ((pos[0] * UR + pos[1] * LEFT) - pos) / 3
        self.add(ArrowVectorField(func))
class SizingAndSpacing(Scene):
    def construct(self):
        func = lambda pos: np.sin(pos[0] / 2) * UR + np.cos(pos[1] / 2) * LEFT
        vf = ArrowVectorField(func, x_range=[-7, 7, 1])
        self.add(vf)
        self.wait()

        length_func = lambda x: x / 3
        vf2 = ArrowVectorField(func, x_range=[-7, 7, 1], length_func=length_func)
        self.play(vf.animate.become(vf2))
        self.wait()
class Coloring(Scene):
    def construct(self):
        func = lambda pos: pos - LEFT * 5
        colors = [RED, YELLOW, BLUE, DARK_GRAY]
        min_radius = Circle(radius=2, color=colors[0]).shift(LEFT * 5)
        max_radius = Circle(radius=10, color=colors[-1]).shift(LEFT * 5)
        vf = ArrowVectorField(
            func, min_color_scheme_value=2, max_color_scheme_value=10, colors=colors
        )
        self.add(vf, min_radius, max_radius)
get_vector(point: ndarray)

Creates a vector in the vector field.

The created vector is based on the function of the vector field and is rooted in the given point. Color and length fit the specifications of this vector field.

Parameters
point

The root point of the vector.

ComplexValueTracker

追踪复数的 ValueTracker:set_value 传复数,get_value 返回 complex,实部虚部同步插值。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Mobject" -> "ValueTracker"; "ValueTracker" -> "ComplexValueTracker"; }

参数

快速上手

z = ComplexValueTracker(1 + 2j)
z.set_value(3 - 1j)

API 文档

class manim.ComplexValueTracker(value: float = 0, **kwargs: Any)

基类:ValueTracker

Tracks a complex-valued parameter.

The value is internally stored as a points array [a, b, 0]. This can be accessed directly to represent the value geometrically, see the usage example. When the value is set through animate, the value will take a straight path from the source point to the destination point.

Examples

class ComplexValueTrackerExample(Scene):
    def construct(self):
        tracker = ComplexValueTracker(-2+1j)
        dot = Dot().add_updater(
            lambda x: x.move_to(tracker.points)
        )

        self.add(NumberPlane(), dot)

        self.play(tracker.animate.set_value(3+2j))
        self.play(tracker.animate.set_value(tracker.get_value() * 1j))
        self.play(tracker.animate.set_value(tracker.get_value() - 2j))
        self.play(tracker.animate.set_value(tracker.get_value() / (-2 + 3j)))
get_value() → complex

Get the current value of this ComplexValueTracker as a complex number.

set_value(value: complex | float) → Self

Sets a new complex value to the ComplexValueTracker.

DecimalMatrix

矩阵 + 每个元素都是可动 DecimalNumber:数值变化动画可直接播在矩阵上。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Mobject" -> "VMobject"; "VMobject" -> "Matrix"; "Matrix" -> "DecimalMatrix"; }

参数

matrix

—,Iterable[Iterable[Any]]

element_to_mobject

<class 'manim.mobject.text.…

element_to_mobject_config

{'num_decimal_places': 1},dict[str, Any]

API 文档

class manim.DecimalMatrix(matrix: ~collections.abc.Iterable[~collections.abc.Iterable[~typing.Any]], element_to_mobject: type[~manim.mobject.types.vectorized_mobject.VMobject] | ~collections.abc.Callable[[...], ~manim.mobject.types.vectorized_mobject.VMobject] = <class 'manim.mobject.text.numbers.DecimalNumber'>, element_to_mobject_config: dict[str, ~typing.Any] = {'num_decimal_places': 1}, **kwargs: ~typing.Any)

基类:Matrix

A mobject that displays a matrix with decimal entries on the screen.

Examples

class DecimalMatrixExample(Scene):
    def construct(self):
        m0 = DecimalMatrix(
            [[3.456, 2.122], [33.2244, 12]],
            element_to_mobject_config={"num_decimal_places": 2},
            left_bracket="\\{",
            right_bracket="\\}")
        self.add(m0)

DecimalTable

表格 + 可动的十进制数字单元格,做数据表动态更新最方便。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Mobject" -> "VMobject"; "VMobject" -> "VGroup"; "VGroup" -> "Table"; "Table" -> "DecimalTable"; }

参数

table

—

element_to_mobject

<class 'manim.mobject.text.…

element_to_mobject_config

{'num_decimal_places': 1},dict

快速上手

table = DecimalTable([[3.14, 2.71], [1.41, 1.73]])

API 文档

class manim.DecimalTable(table: ~collections.abc.Iterable[~collections.abc.Iterable[float | str]], element_to_mobject: ~collections.abc.Callable[[float | str], ~manim.mobject.types.vectorized_mobject.VMobject] | type[~manim.mobject.types.vectorized_mobject.VMobject] = <class 'manim.mobject.text.numbers.DecimalNumber'>, element_to_mobject_config: dict = {'num_decimal_places': 1}, **kwargs: ~typing.Any)

基类:Table

A specialized Table mobject for use with DecimalNumber to display decimal entries.

Examples

class DecimalTableExample(Scene):
    def construct(self):
        x_vals = [-2,-1,0,1,2]
        y_vals = np.exp(x_vals)
        t0 = DecimalTable(
            [x_vals, y_vals],
            row_labels=[MathTex("x"), MathTex("f(x)=e^{x}")],
            h_buff=1,
            element_to_mobject_config={"num_decimal_places": 2})
        self.add(t0)

DiGraph

有向图对象:顶点 + 带箭头的边,支持自动布局与顶点/边样式定制。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Mobject" -> "VMobject"; "VMobject" -> "DiGraph"; }

参数

vertices

—,Sequence[Hashable]

edges

—

labels

False,bool | dict

label_fill_color

ManimColor('#000000'),str

layout

'spring'

layout_scale

2

layout_config

None,dict | None

vertex_type

<class 'manim.mobject.geome…,type[Mobject]

vertex_config

None,dict | None

vertex_mobjects

None,dict | None

edge_type

<class 'manim.mobject.geome…,type[Mobject]

partitions

None

root_vertex

None,Hashable | None

edge_config

None,dict | None

快速上手

g = DiGraph([1, 2, 3], [(1, 2), (2, 3)])

API 文档

class manim.DiGraph(vertices: Sequence[Hashable], edges: Sequence[tuple[Hashable, Hashable]], labels: bool | dict = False, label_fill_color: str = ManimColor('#000000'), layout: LayoutName | dict[Hashable, Point3DLike] | LayoutFunction = 'spring', layout_scale: float | tuple[float, float, float] = 2, layout_config: dict | None = None, vertex_type: type[Mobject] = <class 'manim.mobject.geometry.arc.Dot'>, vertex_config: dict | None = None, vertex_mobjects: dict | None = None, edge_type: type[Mobject] = <class 'manim.mobject.geometry.line.Line'>, partitions: Sequence[Sequence[Hashable]] | None = None, root_vertex: Hashable | None = None, edge_config: dict | None = None)

基类:GenericGraph

A directed graph.

备注

In contrast to undirected graphs, the order in which vertices in a given edge are specified is relevant here.

See also

GenericGraph

Parameters

vertices

A list of vertices. Must be hashable elements.

edges

A list of edges, specified as tuples (u, v) where both u and v are vertices. The edge is directed from u to v.

labels

Controls whether or not vertices are labeled. If False (the default), the vertices are not labeled; if True they are labeled using their names (as specified in vertices) via MathTex. Alternatively, custom labels can be specified by passing a dictionary whose keys are the vertices, and whose values are the corresponding vertex labels (rendered via, e.g., Text or Tex).

label_fill_color

Sets the fill color of the default labels generated when labels is set to True. Has no effect for other values of labels.

layout

Either one of "spring" (the default), "circular", "kamada_kawai", "planar", "random", "shell", "spectral", "spiral", "tree", and "partite" for automatic vertex positioning using networkx (see their documentation for more details), or a dictionary specifying a coordinate (value) for each vertex (key) for manual positioning.

layout_config

Only for automatically generated layouts. A dictionary whose entries are passed as keyword arguments to the automatic layout algorithm specified via layout of networkx. The tree layout also accepts a special parameter vertex_spacing passed as a keyword argument inside the layout_config dictionary. Passing a tuple (space_x, space_y) as this argument overrides the value of layout_scale and ensures that vertices are arranged in a way such that the centers of siblings in the same layer are at least space_x units apart horizontally, and neighboring layers are spaced space_y units vertically.

layout_scale

The scale of automatically generated layouts: the vertices will be arranged such that the coordinates are located within the interval [-scale, scale]. Some layouts accept a tuple (scale_x, scale_y) causing the first coordinate to be in the interval [-scale_x, scale_x], and the second in [-scale_y, scale_y]. Default: 2.

vertex_type

The mobject class used for displaying vertices in the scene.

vertex_config

Either a dictionary containing keyword arguments to be passed to the class specified via vertex_type, or a dictionary whose keys are the vertices, and whose values are dictionaries containing keyword arguments for the mobject related to the corresponding vertex.

vertex_mobjects

A dictionary whose keys are the vertices, and whose values are mobjects to be used as vertices. Passing vertices here overrides all other configuration options for a vertex.

edge_type

The mobject class used for displaying edges in the scene.

edge_config

Either a dictionary containing keyword arguments to be passed to the class specified via edge_type, or a dictionary whose keys are the edges, and whose values are dictionaries containing keyword arguments for the mobject related to the corresponding edge. You can further customize the tip by adding a tip_config dictionary for global styling, or by adding the dict to a specific edge_config.

Examples

class MovingDiGraph(Scene):
    def construct(self):
        vertices = [1, 2, 3, 4]
        edges = [(1, 2), (2, 3), (3, 4), (1, 3), (1, 4)]

        g = DiGraph(vertices, edges)

        self.add(g)
        self.play(
            g[1].animate.move_to([1, 1, 1]),
            g[2].animate.move_to([-1, 1, 2]),
            g[3].animate.move_to([1, -1, -1]),
            g[4].animate.move_to([-1, -1, 0]),
        )
        self.wait()

You can customize the edges and arrow tips globally or locally.

class CustomDiGraph(Scene):
    def construct(self):
        vertices = [i for i in range(5)]
        edges = [
            (0, 1),
            (1, 2),
            (3, 2),
            (3, 4),
        ]

        edge_config = {
            "stroke_width": 2,
            "tip_config": {
                "tip_shape": ArrowSquareTip,
                "tip_length": 0.15,
            },
            (3, 4): {
                "color": RED,
                "tip_config": {"tip_length": 0.25, "tip_width": 0.25}
            },
        }

        g = DiGraph(
            vertices,
            edges,
            labels=True,
            layout="circular",
            edge_config=edge_config,
        ).scale(1.4)

        self.play(Create(g))
        self.wait()

Since this implementation respects the labels boundary you can also use it for an undirected moving graph with labels.

class UndirectedMovingDiGraph(Scene):
    def construct(self):
        vertices = [i for i in range(5)]
        edges = [
            (0, 1),
            (1, 2),
            (3, 2),
            (3, 4),
        ]

        edge_config = {
            "stroke_width": 2,
            "tip_config": {"tip_length": 0, "tip_width": 0},
            (3, 4): {"color": RED},
        }

        g = DiGraph(
            vertices,
            edges,
            labels=True,
            layout="circular",
            edge_config=edge_config,
        ).scale(1.4)

        self.play(Create(g))
        self.wait()

        self.play(
            g[1].animate.move_to([1, 1, 1]),
            g[2].animate.move_to([-1, 1, 2]),
            g[3].animate.move_to([-1.5, -1.5, -1]),
            g[4].animate.move_to([1, -2, -1]),
        )
        self.wait()
update_edges(graph) → Self

Updates the edges to stick at their corresponding vertices.

Arrow tips need to be repositioned since otherwise they can be deformed.

FullScreenRectangle

恰好铺满整个画面(含边距)的矩形,常作背景板或全屏遮罩。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Mobject" -> "VMobject"; "VMobject" -> "Polygram"; "Polygram" -> "Polygon"; "Polygon" -> "Rectangle"; "Rectangle" -> "ScreenRectangle"; "ScreenRectangle" -> "FullScreenRectangle"; }

快速上手

bg = FullScreenRectangle(fill_color=BLACK, fill_opacity=0.8)

API 文档

class manim.FullScreenRectangle(**kwargs: Any)

基类:ScreenRectangle

Graph

通用图论对象:无向图,自动布局(如 spring/circular),顶点标签、边粗细颜色全能调。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Mobject" -> "VMobject"; "VMobject" -> "Graph"; }

参数

vertices

—,Sequence[Hashable]

edges

—

labels

False,bool | dict

label_fill_color

ManimColor('#000000'),str

layout

'spring'

layout_scale

2

layout_config

None,dict | None

vertex_type

<class 'manim.mobject.geome…,type[Mobject]

vertex_config

None,dict | None

vertex_mobjects

None,dict | None

edge_type

<class 'manim.mobject.geome…,type[Mobject]

partitions

None

root_vertex

None,Hashable | None

edge_config

None,dict | None

快速上手

g = Graph([1, 2, 3], [(1, 2), (2, 3), (3, 1)])

API 文档

class manim.Graph(vertices: Sequence[Hashable], edges: Sequence[tuple[Hashable, Hashable]], labels: bool | dict = False, label_fill_color: str = ManimColor('#000000'), layout: LayoutName | dict[Hashable, Point3DLike] | LayoutFunction = 'spring', layout_scale: float | tuple[float, float, float] = 2, layout_config: dict | None = None, vertex_type: type[Mobject] = <class 'manim.mobject.geometry.arc.Dot'>, vertex_config: dict | None = None, vertex_mobjects: dict | None = None, edge_type: type[Mobject] = <class 'manim.mobject.geometry.line.Line'>, partitions: Sequence[Sequence[Hashable]] | None = None, root_vertex: Hashable | None = None, edge_config: dict | None = None)

基类:GenericGraph

An undirected graph (vertices connected with edges).

The graph comes with an updater which makes the edges stick to the vertices when moved around. See DiGraph for a version with directed edges.

See also

GenericGraph

Parameters

vertices

A list of vertices. Must be hashable elements.

edges

A list of edges, specified as tuples (u, v) where both u and v are vertices. The vertex order is irrelevant.

labels

Controls whether or not vertices are labeled. If False (the default), the vertices are not labeled; if True they are labeled using their names (as specified in vertices) via MathTex. Alternatively, custom labels can be specified by passing a dictionary whose keys are the vertices, and whose values are the corresponding vertex labels (rendered via, e.g., Text or Tex).

label_fill_color

Sets the fill color of the default labels generated when labels is set to True. Has no effect for other values of labels.

layout

Either one of "spring" (the default), "circular", "kamada_kawai", "planar", "random", "shell", "spectral", "spiral", "tree", and "partite" for automatic vertex positioning using networkx (see their documentation for more details), or a dictionary specifying a coordinate (value) for each vertex (key) for manual positioning.

layout_config

Only for automatically generated layouts. A dictionary whose entries are passed as keyword arguments to the automatic layout algorithm specified via layout of networkx. The tree layout also accepts a special parameter vertex_spacing passed as a keyword argument inside the layout_config dictionary. Passing a tuple (space_x, space_y) as this argument overrides the value of layout_scale and ensures that vertices are arranged in a way such that the centers of siblings in the same layer are at least space_x units apart horizontally, and neighboring layers are spaced space_y units vertically.

layout_scale

The scale of automatically generated layouts: the vertices will be arranged such that the coordinates are located within the interval [-scale, scale]. Some layouts accept a tuple (scale_x, scale_y) causing the first coordinate to be in the interval [-scale_x, scale_x], and the second in [-scale_y, scale_y]. Default: 2.

vertex_type

The mobject class used for displaying vertices in the scene.

vertex_config

Either a dictionary containing keyword arguments to be passed to the class specified via vertex_type, or a dictionary whose keys are the vertices, and whose values are dictionaries containing keyword arguments for the mobject related to the corresponding vertex.

vertex_mobjects

A dictionary whose keys are the vertices, and whose values are mobjects to be used as vertices. Passing vertices here overrides all other configuration options for a vertex.

edge_type

The mobject class used for displaying edges in the scene.

edge_config

Either a dictionary containing keyword arguments to be passed to the class specified via edge_type, or a dictionary whose keys are the edges, and whose values are dictionaries containing keyword arguments for the mobject related to the corresponding edge.

Examples

First, we create a small graph and demonstrate that the edges move together with the vertices.

class MovingVertices(Scene):
    def construct(self):
        vertices = [1, 2, 3, 4]
        edges = [(1, 2), (2, 3), (3, 4), (1, 3), (1, 4)]
        g = Graph(vertices, edges)
        self.play(Create(g))
        self.wait()
        self.play(g[1].animate.move_to([1, 1, 0]),
                  g[2].animate.move_to([-1, 1, 0]),
                  g[3].animate.move_to([1, -1, 0]),
                  g[4].animate.move_to([-1, -1, 0]))
        self.play(LaggedStart(Wiggle(g[(1, 2)]),
                              Wiggle(g[(2, 3)]),
                              Wiggle(g[(3, 4)]),
                              Wiggle(g[(1, 3)]),
                              Wiggle(g[(1, 4)])))
        self.wait()

There are several automatic positioning algorithms to choose from:

class GraphAutoPosition(Scene):
    def construct(self):
        vertices = [1, 2, 3, 4, 5, 6, 7, 8]
        edges = [(1, 7), (1, 8), (2, 3), (2, 4), (2, 5),
                 (2, 8), (3, 4), (6, 1), (6, 2),
                 (6, 3), (7, 2), (7, 4)]
        autolayouts = ["spring", "circular", "kamada_kawai",
                       "planar", "random", "shell",
                       "spectral", "spiral"]
        graphs = [Graph(vertices, edges, layout=lt).scale(0.5)
                  for lt in autolayouts]
        r1 = VGroup(*graphs[:3]).arrange()
        r2 = VGroup(*graphs[3:6]).arrange()
        r3 = VGroup(*graphs[6:]).arrange()
        self.add(VGroup(r1, r2, r3).arrange(direction=DOWN))

Vertices can also be positioned manually:

class GraphManualPosition(Scene):
    def construct(self):
        vertices = [1, 2, 3, 4]
        edges = [(1, 2), (2, 3), (3, 4), (4, 1)]
        lt = {1: [0, 0, 0], 2: [1, 1, 0], 3: [1, -1, 0], 4: [-1, 0, 0]}
        G = Graph(vertices, edges, layout=lt)
        self.add(G)

The vertices in graphs can be labeled, and configurations for vertices and edges can be modified both by default and for specific vertices and edges.

备注

In edge_config, edges can be passed in both directions: if (u, v) is an edge in the graph, both (u, v) as well as (v, u) can be used as keys in the dictionary.

class LabeledModifiedGraph(Scene):
    def construct(self):
        vertices = [1, 2, 3, 4, 5, 6, 7, 8]
        edges = [(1, 7), (1, 8), (2, 3), (2, 4), (2, 5),
                 (2, 8), (3, 4), (6, 1), (6, 2),
                 (6, 3), (7, 2), (7, 4)]
        g = Graph(vertices, edges, layout="circular", layout_scale=3,
                  labels=True, vertex_config={7: {"fill_color": RED}},
                  edge_config={(1, 7): {"stroke_color": RED},
                               (2, 7): {"stroke_color": RED},
                               (4, 7): {"stroke_color": RED}})
        self.add(g)

You can also lay out a partite graph on columns by specifying a list of the vertices on each side and choosing the partite layout.

备注

All vertices in your graph which are not listed in any of the partitions are collected in their own partition and rendered in the rightmost column.

import networkx as nx

class PartiteGraph(Scene):
    def construct(self):
        G = nx.Graph()
        G.add_nodes_from([0, 1, 2, 3])
        G.add_edges_from([(0, 2), (0,3), (1, 2)])
        graph = Graph(list(G.nodes), list(G.edges), layout="partite", partitions=[[0, 1]])
        self.play(Create(graph))

The representation of a linear artificial neural network is facilitated by the use of the partite layout and defining partitions for each layer.

class LinearNN(Scene):
    def construct(self):
        edges = []
        partitions = []
        c = 0
        layers = [2, 3, 3, 2]  # the number of neurons in each layer

        for i in layers:
            partitions.append(list(range(c + 1, c + i + 1)))
            c += i
        for i, v in enumerate(layers[1:]):
                last = sum(layers[:i+1])
                for j in range(v):
                    for k in range(last - layers[i], last):
                        edges.append((k + 1, j + last + 1))

        vertices = np.arange(1, sum(layers) + 1)

        graph = Graph(
            vertices,
            edges,
            layout='partite',
            partitions=partitions,
            layout_scale=3,
            vertex_config={'radius': 0.20},
        )
        self.add(graph)

The custom tree layout can be used to show the graph by distance from the root vertex. You must pass the root vertex of the tree.

import networkx as nx

class Tree(Scene):
    def construct(self):
        G = nx.Graph()

        G.add_node("ROOT")

        for i in range(5):
            G.add_node("Child_%i" % i)
            G.add_node("Grandchild_%i" % i)
            G.add_node("Greatgrandchild_%i" % i)

            G.add_edge("ROOT", "Child_%i" % i)
            G.add_edge("Child_%i" % i, "Grandchild_%i" % i)
            G.add_edge("Grandchild_%i" % i, "Greatgrandchild_%i" % i)

        self.play(Create(
            Graph(list(G.nodes), list(G.edges), layout="tree", root_vertex="ROOT")))

The following code sample illustrates the use of the vertex_spacing layout parameter specific to the "tree" layout. As mentioned above, setting vertex_spacing overrides the specified value for layout_scale, and as such it is harder to control the size of the mobject. However, we can adjust the captured frame and zoom out by using a MovingCameraScene:

class LargeTreeGeneration(MovingCameraScene):
    DEPTH = 4
    CHILDREN_PER_VERTEX = 3
    LAYOUT_CONFIG = {"vertex_spacing": (0.5, 1)}
    VERTEX_CONF = {"radius": 0.25, "color": BLUE_B, "fill_opacity": 1}

    def expand_vertex(self, g, vertex_id: str, depth: int):
        new_vertices = [
            f"{vertex_id}/{i}" for i in range(self.CHILDREN_PER_VERTEX)
        ]
        new_edges = [(vertex_id, child_id) for child_id in new_vertices]
        g.add_edges(
            *new_edges,
            vertex_config=self.VERTEX_CONF,
            positions={
                k: g.vertices[vertex_id].get_center() + 0.1 * DOWN
                for k in new_vertices
            },
        )
        if depth < self.DEPTH:
            for child_id in new_vertices:
                self.expand_vertex(g, child_id, depth + 1)

        return g

    def construct(self):
        g = Graph(["ROOT"], [], vertex_config=self.VERTEX_CONF)
        g = self.expand_vertex(g, "ROOT", 1)
        self.add(g)

        self.play(
            g.animate.change_layout(
                "tree",
                root_vertex="ROOT",
                layout_config=self.LAYOUT_CONFIG,
            )
        )
        self.play(self.camera.auto_zoom(g, margin=1), run_time=0.5)

Group

Mobject 的通用容器:把任意对象打包统一管理(移动、淡入、整体动画)。注意 Group 不保证子对象是 VMobject。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Mobject" -> "Group"; }

快速上手

group = Group(dot, label, square)
self.play(FadeIn(group))

API 文档

class manim.Group(*mobjects: Any, **kwargs: Any)

基类:Mobject

Groups together multiple Mobjects.

Notes

When adding the same mobject more than once, repetitions are ignored. Use Mobject.copy() to create a separate copy which can then be added to the group.

IntegerMatrix

元素为整数的矩阵 Mobject,和 DecimalMatrix 类似但用固定整数显示。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Mobject" -> "VMobject"; "VMobject" -> "Matrix"; "Matrix" -> "IntegerMatrix"; }

参数

matrix

—,Iterable[Iterable[Any]]

element_to_mobject

<class 'manim.mobject.text.…

API 文档

class manim.IntegerMatrix(matrix: ~collections.abc.Iterable[~collections.abc.Iterable[~typing.Any]], element_to_mobject: type[~manim.mobject.types.vectorized_mobject.VMobject] | ~collections.abc.Callable[[...], ~manim.mobject.types.vectorized_mobject.VMobject] = <class 'manim.mobject.text.numbers.Integer'>, **kwargs: ~typing.Any)

基类:Matrix

A mobject that displays a matrix with integer entries on the screen.

Examples

class IntegerMatrixExample(Scene):
    def construct(self):
        m0 = IntegerMatrix(
            [[3.7, 2], [42.2, 12]],
            left_bracket="(",
            right_bracket=")")
        self.add(m0)

IntegerTable

整数单元格表格,适合计数类数据展示。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Mobject" -> "VMobject"; "VMobject" -> "VGroup"; "VGroup" -> "Table"; "Table" -> "IntegerTable"; }

参数

table

—

element_to_mobject

<class 'manim.mobject.text.…

API 文档

class manim.IntegerTable(table: ~collections.abc.Iterable[~collections.abc.Iterable[float | str]], element_to_mobject: ~collections.abc.Callable[[float | str], ~manim.mobject.types.vectorized_mobject.VMobject] | type[~manim.mobject.types.vectorized_mobject.VMobject] = <class 'manim.mobject.text.numbers.Integer'>, **kwargs: ~typing.Any)

基类:Table

A specialized Table mobject for use with Integer.

Examples

class IntegerTableExample(Scene):
    def construct(self):
        t0 = IntegerTable(
            [[0,30,45,60,90],
            [90,60,45,30,0]],
            col_labels=[
                MathTex(r"\frac{ \sqrt{0} }{2}"),
                MathTex(r"\frac{ \sqrt{1} }{2}"),
                MathTex(r"\frac{ \sqrt{2} }{2}"),
                MathTex(r"\frac{ \sqrt{3} }{2}"),
                MathTex(r"\frac{ \sqrt{4} }{2}")],
            row_labels=[MathTex(r"\sin"), MathTex(r"\cos")],
            h_buff=1,
            element_to_mobject_config={"unit": r"^{\circ}"})
        self.add(t0)

ManimBanner

官方 Logo 动画横幅:自带展开、收拢等现成动画方法,适合视频片头片尾。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Mobject" -> "VMobject"; "VMobject" -> "VGroup"; "VGroup" -> "ManimBanner"; }

参数

快速上手

banner = ManimBanner()
self.play(banner.expand())

API 文档

class manim.ManimBanner(dark_theme: bool = True)

基类:VGroup

Convenience class representing Manim's banner.

Can be animated using custom methods.

Parameters

dark_theme

If True (the default), the dark theme version of the logo (with light text font) will be rendered. Otherwise, if False, the light theme version (with dark text font) is used.

Examples

class DarkThemeBanner(Scene):
    def construct(self):
        banner = ManimBanner()
        self.play(banner.create())
        self.play(banner.expand())
        self.wait()
        self.play(Unwrite(banner))
class LightThemeBanner(Scene):
    def construct(self):
        self.camera.background_color = "#ece6e2"
        banner = ManimBanner(dark_theme=False)
        self.play(banner.create())
        self.play(banner.expand())
        self.wait()
        self.play(Unwrite(banner))
create(run_time: float = 2) → AnimationGroup

The creation animation for Manim's logo.

Parameters
run_time

The run time of the animation.

Returns
AnimationGroup

An animation to be used in a Scene.play() call.

expand(run_time: float = 1.5, direction: str = 'center') → Succession

An animation that expands Manim's logo into its banner.

The returned animation transforms the banner from its initial state (representing Manim's logo with just the icons) to its expanded state (showing the full name together with the icons).

See the class documentation for how to use this.

备注

Before calling this method, the text "anim" is not a submobject of the banner object. After the expansion, it is added as a submobject so subsequent animations to the banner object apply to the text "anim" as well.

Parameters
run_time

The run time of the animation.

direction

The direction in which the logo is expanded.

Returns
Succession

An animation to be used in a Scene.play() call.

Examples
class ExpandDirections(Scene):
    def construct(self):
        banners = [ManimBanner().scale(0.5).shift(UP*x) for x in [-2, 0, 2]]
        self.play(
            banners[0].expand(direction="right"),
            banners[1].expand(direction="center"),
            banners[2].expand(direction="left"),
        )
scale(scale_factor: float, **kwargs: Any) → Self

Scale the banner by the specified scale factor.

Parameters
scale_factor

The factor used for scaling the banner.

Returns
ManimBanner

The scaled banner.

MathTable

单元格为 MathTex 的表格:每个格子都是公式,排版数学矩阵类内容用。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Mobject" -> "VMobject"; "VMobject" -> "VGroup"; "VGroup" -> "Table"; "Table" -> "MathTable"; }

参数

table

—

element_to_mobject

<class 'manim.mobject.text.…

API 文档

class manim.MathTable(table: ~collections.abc.Iterable[~collections.abc.Iterable[float | str]], element_to_mobject: ~collections.abc.Callable[[float | str], ~manim.mobject.types.vectorized_mobject.VMobject] | type[~manim.mobject.types.vectorized_mobject.VMobject] = <class 'manim.mobject.text.tex_mobject.MathTex'>, **kwargs: ~typing.Any)

基类:Table

A specialized Table mobject for use with LaTeX.

Examples

class MathTableExample(Scene):
    def construct(self):
        t0 = MathTable(
            [["+", 0, 5, 10],
            [0, 0, 5, 10],
            [2, 2, 7, 12],
            [4, 4, 9, 14]],
            include_outer_lines=True)
        self.add(t0)

Matrix

通用矩阵对象:元素可以是任意 Mobject,括号、行距列距可调,线性代数章节的核心道具。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Mobject" -> "VMobject"; "VMobject" -> "Matrix"; }

参数

matrix

—

v_buff

0.8,float

h_buff

1.3,float

bracket_h_buff

0.25,float

bracket_v_buff

0.25,float

add_background_rectangles_to_entries

False,bool

include_background_rectangle

False,bool

element_to_mobject

<class 'manim.mobject.text.…

element_to_mobject_config

{},dict[str, Any]

element_alignment_corner

array([ 1., -1., 0.]),Vector3DLike

left_bracket

'[',str

right_bracket

']',str

stretch_brackets

True,bool

bracket_config

{},dict

快速上手

m = Matrix([[1, 2], [3, 4]])

API 文档

class manim.Matrix(matrix: ~collections.abc.Iterable[~collections.abc.Iterable[~typing.Any] | ~numpy._typing._array_like.NDArray[~numpy.float64] | tuple[float, float]], v_buff: float = 0.8, h_buff: float = 1.3, bracket_h_buff: float = 0.25, bracket_v_buff: float = 0.25, add_background_rectangles_to_entries: bool = False, include_background_rectangle: bool = False, element_to_mobject: type[~manim.mobject.types.vectorized_mobject.VMobject] | ~collections.abc.Callable[[...], ~manim.mobject.types.vectorized_mobject.VMobject] = <class 'manim.mobject.text.tex_mobject.MathTex'>, element_to_mobject_config: dict[str, ~typing.Any] = {}, element_alignment_corner: ~numpy._typing._array_like.NDArray[~numpy.float64] | tuple[float, float, float] = array([ 1., -1.,  0.]), left_bracket: str = '[', right_bracket: str = ']', stretch_brackets: bool = True, bracket_config: dict = {}, **kwargs: ~typing.Any)

基类:VMobject

A mobject that displays a matrix on the screen.

Parameters

matrix

A numpy 2d array or list of lists.

v_buff

Vertical distance between elements, by default 0.8.

h_buff

Horizontal distance between elements, by default 1.3.

bracket_h_buff

Distance of the brackets from the matrix, by default MED_SMALL_BUFF.

bracket_v_buff

Height of the brackets, by default MED_SMALL_BUFF.

add_background_rectangles_to_entries

True if should add backgraound rectangles to entries, by default False.

include_background_rectangle

True if should include background rectangle, by default False.

element_to_mobject

The mobject class used to construct the elements, by default MathTex.

element_to_mobject_config

Additional arguments to be passed to the constructor in element_to_mobject, by default {}.

element_alignment_corner

The corner to which elements are aligned, by default DR.

left_bracket

The left bracket type, by default "[".

right_bracket

The right bracket type, by default "]".

stretch_brackets

True if should stretch the brackets to fit the height of matrix contents, by default True.

bracket_config

Additional arguments to be passed to MathTex when constructing the brackets.

Examples

The first example shows a variety of uses of this module while the second example exlpains the use of the options add_background_rectangles_to_entries and include_background_rectangle.

class MatrixExamples(Scene):
    def construct(self):
        m0 = Matrix([[2, r"\pi"], [-1, 1]])
        m1 = Matrix([[2, 0, 4], [-1, 1, 5]],
            v_buff=1.3,
            h_buff=0.8,
            bracket_h_buff=SMALL_BUFF,
            bracket_v_buff=SMALL_BUFF,
            left_bracket=r"\{",
            right_bracket=r"\}")
        m1.add(SurroundingRectangle(m1.get_columns()[1]))
        m2 = Matrix([[2, 1], [-1, 3]],
            element_alignment_corner=UL,
            left_bracket="(",
            right_bracket=")")
        m3 = Matrix([[2, 1], [-1, 3]],
            left_bracket=r"\langle",
            right_bracket=r"\rangle")
        m4 = Matrix([[2, 1], [-1, 3]],
        ).set_column_colors(RED, GREEN)
        m5 = Matrix([[2, 1], [-1, 3]],
        ).set_row_colors(RED, GREEN)
        g = Group(
            m0,m1,m2,m3,m4,m5
        ).arrange_in_grid(buff=2)
        self.add(g)
class BackgroundRectanglesExample(Scene):
    def construct(self):
        background= Rectangle().scale(3.2)
        background.set_fill(opacity=.5)
        background.set_color([TEAL, RED, YELLOW])
        self.add(background)
        m0 = Matrix([[12, -30], [-1, 15]],
            add_background_rectangles_to_entries=True)
        m1 = Matrix([[2, 0], [-1, 1]],
            include_background_rectangle=True)
        m2 = Matrix([[12, -30], [-1, 15]])
        g = Group(m0, m1, m2).arrange(buff=2)
        self.add(g)
add_background_to_entries() → Self

Add a black background rectangle to the matrix, see above for an example.

Returns
Matrix

The current matrix object (self).

get_brackets() → VGroup

Return the bracket mobjects.

Returns
VGroup

A VGroup containing the left and right bracket.

Examples
class GetBracketsExample(Scene):
    def construct(self):
        m0 = Matrix([["\\pi", 3], [1, 5]])
        bra = m0.get_brackets()
        colors = [BLUE, GREEN]
        for k in range(len(colors)):
            bra[k].set_color(colors[k])
        self.add(m0)
get_columns() → VGroup

Return columns of the matrix as VGroups.

Returns
VGroup

The VGroup contains a nested VGroup for each column of the matrix.

Examples
class GetColumnsExample(Scene):
    def construct(self):
        m0 = Matrix([[r"\pi", 3], [1, 5]])
        m0.add(SurroundingRectangle(m0.get_columns()[1]))
        self.add(m0)
get_entries() → VGroup

Return the individual entries of the matrix.

Returns
VGroup

VGroup containing entries of the matrix.

Examples
class GetEntriesExample(Scene):
    def construct(self):
        m0 = Matrix([[2, 3], [1, 5]])
        ent = m0.get_entries()
        colors = [BLUE, GREEN, YELLOW, RED]
        for k in range(len(colors)):
            ent[k].set_color(colors[k])
        self.add(m0)
get_mob_matrix() → list[list[VMobject]]

Return the underlying mob matrix mobjects.

Returns
List[VGroup]

Each VGroup contains a row of the matrix.

get_rows() → VGroup

Return rows of the matrix as VGroups.

Returns
VGroup

The VGroup contains a nested VGroup for each row of the matrix.

Examples
class GetRowsExample(Scene):
    def construct(self):
        m0 = Matrix([["\\pi", 3], [1, 5]])
        m0.add(SurroundingRectangle(m0.get_rows()[1]))
        self.add(m0)
set_column_colors(*colors: str) → Self

Set individual colors for each columns of the matrix.

Parameters
colors

The list of colors; each color specified corresponds to a column.

Returns
Matrix

The current matrix object (self).

Examples
class SetColumnColorsExample(Scene):
    def construct(self):
        m0 = Matrix([["\\pi", 1], [-1, 3]],
        ).set_column_colors([RED,BLUE], GREEN)
        self.add(m0)
set_row_colors(*colors: str) → Self

Set individual colors for each row of the matrix.

Parameters
colors

The list of colors; each color specified corresponds to a row.

Returns
Matrix

The current matrix object (self).

Examples
class SetRowColorsExample(Scene):
    def construct(self):
        m0 = Matrix([["\\pi", 1], [-1, 3]],
        ).set_row_colors([RED,BLUE], GREEN)
        self.add(m0)

Mobject

一切可见对象的基类。掌握它的 transform、shift、scale、fade 族方法与子对象树,就掌握了 Manim 的对象模型。

参数

color

ManimColor('#FFFFFF')

name

None,str | None

dim

3,int

target

None,Mobject | None

z_index

0,float

快速上手

mob = Mobject()
mob.shift(UP).scale(2)

API 文档

class manim.Mobject(color: ManimColor | int | str | NDArray[int64] | tuple[int, int, int] | NDArray[float64] | tuple[float, float, float] | tuple[int, int, int, int] | tuple[float, float, float, float] | list[ManimColor | int | str | NDArray[int64] | tuple[int, int, int] | NDArray[float64] | tuple[float, float, float] | tuple[int, int, int, int] | tuple[float, float, float, float]] = ManimColor('#FFFFFF'), name: str | None = None, dim: int = 3, target: Mobject | None = None, z_index: float = 0)

基类:object

Mathematical Object: base class for objects that can be displayed on screen.

There is a compatibility layer that allows for getting and setting generic attributes with get_* and set_* methods. See set() for more details.

Attributes

submobjectsList[Mobject]

The contained objects.

pointsnumpy.ndarray

The points of the objects.

参见

VMobject

add(*mobjects: Mobject) → Self

Add mobjects as submobjects.

The mobjects are added to submobjects.

Subclasses of mobject may implement + and += dunder methods.

Parameters
mobjects

The mobjects to add.

Returns
Mobject

self

Raises
ValueError

When a mobject tries to add itself.

TypeError

When trying to add an object that is not an instance of Mobject.

Notes

A mobject cannot contain itself, and it cannot contain a submobject more than once. If the parent mobject is displayed, the newly-added submobjects will also be displayed (i.e. they are automatically added to the parent Scene).

See Also

remove() add_to_back()

Examples
>>> outer = Mobject()
>>> inner = Mobject()
>>> outer = outer.add(inner)

Duplicates are not added again:

>>> outer = outer.add(inner)
>>> len(outer.submobjects)
1

Only Mobjects can be added:

>>> outer.add(3)
Traceback (most recent call last):
...
TypeError: Only values of type Mobject can be added as submobjects of Mobject, but the value 3 (at index 0) is of type int.

Adding an object to itself raises an error:

>>> outer.add(outer)
Traceback (most recent call last):
...
ValueError: Cannot add Mobject as a submobject of itself (at index 0).

A given mobject cannot be added as a submobject twice to some parent:

>>> parent = Mobject(name="parent")
>>> child = Mobject(name="child")
>>> parent.add(child, child)
[...] WARNING  ...
parent
>>> parent.submobjects
[child]
classmethod add_animation_override(animation_class: type[Animation], override_func: FunctionOverride) → None

Add an animation override.

This does not apply to subclasses.

Parameters
animation_class

The animation type to be overridden

override_func

The function returning an animation replacing the default animation. It gets passed the parameters given to the animation constructor.

Raises
MultiAnimationOverrideException

If the overridden animation was already overridden.

add_background_rectangle(color: ParsableManimColor | None = None, opacity: float = 0.75, **kwargs: Any) → Self

Add a BackgroundRectangle as submobject.

The BackgroundRectangle is added behind other submobjects.

This can be used to increase the mobjects visibility in front of a noisy background.

Parameters
color

The color of the BackgroundRectangle

opacity

The opacity of the BackgroundRectangle

kwargs

Additional keyword arguments passed to the BackgroundRectangle constructor

Returns
Mobject

self

See Also

add_to_back() BackgroundRectangle

add_to_back(*mobjects: Mobject) → Self

Add all passed mobjects to the back of the submobjects.

If submobjects already contains the given mobjects, they just get moved to the back instead.

Parameters
mobjects

The mobjects to add.

Returns
Mobject

self

备注

Technically, this is done by adding (or moving) the mobjects to the head of submobjects. The head of this list is rendered first, which places the corresponding mobjects behind the subsequent list members.

Raises
ValueError

When a mobject tries to add itself.

TypeError

When trying to add an object that is not an instance of Mobject.

Notes

A mobject cannot contain itself, and it cannot contain a submobject more than once. If the parent mobject is displayed, the newly-added submobjects will also be displayed (i.e. they are automatically added to the parent Scene).

See Also

remove() add()

add_updater(update_function: _Updater, index: int | None = None, call_updater: bool = False) → Self

Add an update function to this mobject.

Update functions, or updaters in short, are functions that are applied to the Mobject in every frame.

Parameters
update_function

The update function to be added. Whenever update() is called, this update function gets called using self as the first parameter. The updater can have a second parameter dt. If it uses this parameter, it gets called using a second value dt, usually representing the time in seconds since the last call of update().

index

The index at which the new updater should be added in self.updaters. In case index is None the updater will be added at the end.

call_updater

Whether or not to call the updater initially. If True, the updater will be called using dt=0.

Returns
Mobject

self

Examples
class NextToUpdater(Scene):
    def construct(self):
        def update_label(mobject):
            mobject.set_value(dot.get_center()[0])
            mobject.next_to(dot)

        dot = Dot(RIGHT*3)
        label = DecimalNumber()
        label.add_updater(update_label)
        self.add(dot, label)

        self.play(Rotating(dot, angle=TAU, about_point=ORIGIN, run_time=TAU, rate_func=linear))
class DtUpdater(Scene):
    def construct(self):
        square = Square()

        #Let the square rotate 90° per second
        square.add_updater(lambda mobject, dt: mobject.rotate(dt*90*DEGREES))
        self.add(square)
        self.wait(2)
See also

get_updaters() remove_updater() UpdateFromFunc Rotating rotate() animate

align_data(mobject: Mobject, skip_point_alignment: bool = False) → Self

Aligns the family structure and data of this mobject with another mobject.

Afterwards, the two mobjects will have the same number of submobjects (see align_submobjects()) and the same parent structure (see null_point_align()). If skip_point_alignment is False, they will also have the same number of points (see align_points()).

Parameters
mobject

The other mobject this mobject should be aligned to.

skip_point_alignment

Controls whether or not the computationally expensive point alignment is skipped (default: False).

备注

This method is primarily used internally by become() and the Transform animation to ensure that mobjects are structurally compatible before transformation.

Examples
>>> from manim import Rectangle, Line, ORIGIN, RIGHT
>>> rect = Rectangle(width=4.0, height=2.0, grid_xstep=1.0, grid_ystep=0.5)
>>> line = Line(start=ORIGIN,end=RIGHT)
>>> line.align_data(rect)
Line
>>> len(line.get_family()) == len(rect.get_family())
True
>>> line.get_num_points() == rect.get_num_points()
True
See also

Transform, become(), align_points(), get_family()

align_on_border(direction: Vector3DLike, buff: float = 0.5) → Self

Direction just needs to be a vector pointing towards side or corner in the 2d plane.

align_to(mobject_or_point: Mobject | Point3DLike, direction: Vector3DLike = array([0., 0., 0.])) → Self

Aligns mobject to another Mobject in a certain direction.

Examples: mob1.align_to(mob2, UP) moves mob1 vertically so that its top edge lines ups with mob2's top edge.

property always: Self

Call a method on a mobject every frame.

This is syntactic sugar for mob.add_updater(lambda m: m.method(``*args, **kwargs), call_updater=True)``. Note that this will call the method immediately. If this behavior is not desired, you should use add_updater() directly.

警告

Chaining of methods is allowed, but each method will be added as its own updater. If you are chaining methods, make sure they do not interfere with each other or you may get unexpected results.

警告

always is not compatible with ValueTracker.get_value(), because the value will be computed once and then never updated again. Use add_updater() if you would like to use a ValueTracker to update the value.

Example
class AlwaysExample(Scene):
    def construct(self):
        sq = Square().to_edge(LEFT)
        t = Text("Hello World!")
        t.always.next_to(sq, UP)
        self.add(sq, t)
        self.play(sq.animate.to_edge(RIGHT))
property animate: _AnimationBuilder | Self

Used to animate the application of any method of self.

Any method called on animate is converted to an animation of applying that method on the mobject itself.

For example, square.set_fill(WHITE) sets the fill color of a square, while square.animate.set_fill(WHITE) animates this action.

Multiple methods can be put in a single animation once via chaining:

self.play(my_mobject.animate.shift(RIGHT).rotate(PI))

警告

Passing multiple animations for the same Mobject in one call to play() is discouraged and will most likely not work properly. Instead of writing an animation like

self.play(
    my_mobject.animate.shift(RIGHT), my_mobject.animate.rotate(PI)
)

make use of method chaining.

Keyword arguments that can be passed to Scene.play() can be passed directly after accessing .animate, like so:

self.play(my_mobject.animate(rate_func=linear).shift(RIGHT))

This is especially useful when animating simultaneous .animate calls that you want to behave differently:

self.play(
    mobject1.animate(run_time=2).rotate(PI),
    mobject2.animate(rate_func=there_and_back).shift(RIGHT),
)

参见

override_animate()

Examples
class AnimateExample(Scene):
    def construct(self):
        s = Square()
        self.play(Create(s))
        self.play(s.animate.shift(RIGHT))
        self.play(s.animate.scale(2))
        self.play(s.animate.rotate(PI / 2))
        self.play(Uncreate(s))
class AnimateChainExample(Scene):
    def construct(self):
        s = Square()
        self.play(Create(s))
        self.play(s.animate.shift(RIGHT).scale(2).rotate(PI / 2))
        self.play(Uncreate(s))
class AnimateWithArgsExample(Scene):
    def construct(self):
        s = Square()
        c = Circle()

        VGroup(s, c).arrange(RIGHT, buff=2)
        self.add(s, c)

        self.play(
            s.animate(run_time=2).rotate(PI / 2),
            c.animate(rate_func=there_and_back).shift(RIGHT),
        )

警告

.animate

will interpolate the Mobject between its points prior to .animate and its points after applying .animate to it. This may result in unexpected behavior when attempting to interpolate along paths, or rotations (see rotate()). If you want animations to consider the points between, consider using ValueTracker with updaters instead (see add_updater()).

classmethod animation_override_for(animation_class: type[Animation]) → FunctionOverride | None

Returns the function defining a specific animation override for this class.

Parameters
animation_class

The animation class for which the override function should be returned.

Returns
Optional[Callable[[Mobject, ...], Animation]]

The function returning the override animation or None if no such animation override is defined.

apply_complex_function(function: Callable[[complex], complex], *, about_point: Point3DLike | None = None, about_edge: Vector3DLike | None = None) → Self

Applies a complex function to a Mobject. The x and y Point3Ds correspond to the real and imaginary parts respectively.

Example
class ApplyFuncExample(Scene):
    def construct(self):
        circ = Circle().scale(1.5)
        circ_ref = circ.copy()
        circ.apply_complex_function(
            lambda x: np.exp(x*1j)
        )
        t = ValueTracker(0)
        circ.add_updater(
            lambda x: x.become(circ_ref.copy().apply_complex_function(
                lambda x: np.exp(x+t.get_value()*1j)
            )).set_color(BLUE)
        )
        self.add(circ_ref)
        self.play(TransformFromCopy(circ_ref, circ))
        self.play(t.animate.set_value(TAU), run_time=3)
apply_to_family(func: Callable[[Mobject], None]) → Self

Apply a function to self and every submobject with points recursively.

Parameters
func

The function to apply to each mobject. func gets passed the respective (sub)mobject as parameter.

Returns
Mobject

self

See also

family_members_with_points()

arrange(direction: Vector3DLike = array([1., 0., 0.]), buff: float = 0.25, center: bool = True, **kwargs: Any) → Self

Sorts Mobject next to each other on screen.

Examples
class Example(Scene):
    def construct(self):
        s1 = Square()
        s2 = Square()
        s3 = Square()
        s4 = Square()
        x = VGroup(s1, s2, s3, s4).set_x(0).arrange(buff=1.0)
        self.add(x)
arrange_in_grid(rows: int | None = None, cols: int | None = None, buff: float | tuple[float, float] = 0.25, cell_alignment: Vector3DLike = array([0., 0., 0.]), row_alignments: str | None = None, col_alignments: str | None = None, row_heights: Iterable[float | None] | None = None, col_widths: Iterable[float | None] | None = None, flow_order: str = 'rd', **kwargs: Any) → Self

Arrange submobjects in a grid.

Parameters
rows

The number of rows in the grid.

cols

The number of columns in the grid.

buff

The gap between grid cells. To specify a different buffer in the horizontal and vertical directions, a tuple of two values can be given - (row, col).

cell_alignment

The way each submobject is aligned in its grid cell.

row_alignments

The vertical alignment for each row (top to bottom). Accepts the following characters: "u" - up, "c" - center, "d" - down.

col_alignments

The horizontal alignment for each column (left to right). Accepts the following characters "l" - left, "c" - center, "r" - right.

row_heights

Defines a list of heights for certain rows (top to bottom). If the list contains None, the corresponding row will fit its height automatically based on the highest element in that row.

col_widths

Defines a list of widths for certain columns (left to right). If the list contains None, the corresponding column will fit its width automatically based on the widest element in that column.

flow_order

The order in which submobjects fill the grid. Can be one of the following values: "rd", "dr", "ld", "dl", "ru", "ur", "lu", "ul". ("rd" -> fill rightwards then downwards)

Returns
Mobject

self

Raises
ValueError

If rows and cols are too small to fit all submobjects.

ValueError

If cols, col_alignments and col_widths or rows, row_alignments and row_heights have mismatching sizes.

Notes

If only one of cols and rows is set implicitly, the other one will be chosen big enough to fit all submobjects. If neither is set, they will be chosen to be about the same, tending towards cols > rows (simply because videos are wider than they are high).

If both cell_alignment and row_alignments / col_alignments are defined, the latter has higher priority.

Examples
class ExampleBoxes(Scene):
    def construct(self):
        boxes=VGroup(*[Square() for s in range(0,6)])
        boxes.arrange_in_grid(rows=2, buff=0.1)
        self.add(boxes)
class ArrangeInGrid(Scene):
    def construct(self):
        boxes = VGroup(*[
            Rectangle(WHITE, 0.5, 0.5).add(Text(str(i+1)).scale(0.5))
            for i in range(24)
        ])
        self.add(boxes)

        boxes.arrange_in_grid(
            buff=(0.25,0.5),
            col_alignments="lccccr",
            row_alignments="uccd",
            col_widths=[1, *[None]*4, 1],
            row_heights=[1, None, None, 1],
            flow_order="dr"
        )
arrange_submobjects(*args: Any, **kwargs: Any) → Self

Arrange the position of submobjects with a small buffer.

Examples
class ArrangeSumobjectsExample(Scene):
    def construct(self):
        s= VGroup(*[Dot().shift(i*0.1*RIGHT*np.random.uniform(-1,1)+UP*np.random.uniform(-1,1)) for i in range(0,15)])
        s.shift(UP).set_color(BLUE)
        s2= s.copy().set_color(RED)
        s2.arrange_submobjects()
        s2.shift(DOWN)
        self.add(s,s2)
become(mobject: Mobject, match_height: bool = False, match_width: bool = False, match_depth: bool = False, match_center: bool = False, stretch: bool = False) → Self

Edit points, colors and submobjects to be identical to another Mobject

备注

If both match_height and match_width are True then the transformed Mobject will match the height first and then the width.

Parameters
match_height

Whether or not to preserve the height of the original Mobject.

match_width

Whether or not to preserve the width of the original Mobject.

match_depth

Whether or not to preserve the depth of the original Mobject.

match_center

Whether or not to preserve the center of the original Mobject.

stretch

Whether or not to stretch the target mobject to match the the proportions of the original Mobject.

Examples
class BecomeScene(Scene):
    def construct(self):
        circ = Circle(fill_color=RED, fill_opacity=0.8)
        square = Square(fill_color=BLUE, fill_opacity=0.2)
        self.add(circ)
        self.wait(0.5)
        circ.become(square)
        self.wait(0.5)

The following examples illustrate how mobject measurements change when using the match_... and stretch arguments. We start with a rectangle that is 2 units high and 4 units wide, which we want to turn into a circle of radius 3:

>>> from manim import Rectangle, Circle
>>> import numpy as np
>>> rect = Rectangle(height=2, width=4)
>>> circ = Circle(radius=3)

With stretch=True, the target circle is deformed to match the proportions of the rectangle, which results in the target mobject being an ellipse with height 2 and width 4. We can check that the resulting points satisfy the ellipse equation \(x^2/a^2 + y^2/b^2 = 1\) with \(a = 4/2\) and \(b = 2/2\) being the semi-axes:

>>> result = rect.copy().become(circ, stretch=True)
>>> result.height, result.width
(np.float64(2.0), np.float64(4.0))
>>> ellipse_points = np.array(result.get_anchors())
>>> ellipse_eq = np.sum(ellipse_points**2 * [1/4, 1, 0], axis=1)
>>> np.allclose(ellipse_eq, 1)
True

With match_height=True and match_width=True the circle is scaled such that the height or the width of the rectangle will be preserved, respectively. The points of the resulting mobject satisfy the circle equation \(x^2 + y^2 = r^2\) for the corresponding radius \(r\):

>>> result = rect.copy().become(circ, match_height=True)
>>> result.height, result.width
(np.float64(2.0), np.float64(2.0))
>>> circle_points = np.array(result.get_anchors())
>>> circle_eq = np.sum(circle_points**2, axis=1)
>>> np.allclose(circle_eq, 1)
True
>>> result = rect.copy().become(circ, match_width=True)
>>> result.height, result.width
(np.float64(4.0), np.float64(4.0))
>>> circle_points = np.array(result.get_anchors())
>>> circle_eq = np.sum(circle_points**2, axis=1)
>>> np.allclose(circle_eq, 2**2)
True

With match_center=True, the resulting mobject is moved such that its center is the same as the center of the original mobject:

>>> rect = rect.shift(np.array([0, 1, 0]))
>>> np.allclose(rect.get_center(), circ.get_center())
False
>>> result = rect.copy().become(circ, match_center=True)
>>> np.allclose(rect.get_center(), result.get_center())
True
See also

align_data(), interpolate_color()

center() → Self

Moves the center of the mobject to the center of the scene.

Returns
Mobject

The centered mobject.

clear_updaters(recursive: bool = True) → Self

Remove every updater.

Parameters
recursive

Whether to recursively call clear_updaters on all submobjects.

Returns
Mobject

self

See also

remove_updater() add_updater() get_updaters()

copy() → Self

Create and return an identical copy of the Mobject including all submobjects.

Returns
Mobject

The copy.

Note

The clone is initially not visible in the Scene, even if the original was.

property depth: float

The depth of the mobject.

Returns

float

See also

length_over_dim()

family_members_with_points() → list[Mobject]

Filters the list of family members (generated by get_family()) to include only mobjects with points.

Returns
list[Mobject]

A list of mobjects that have points.

Examples
>>> from manim import Square, Rectangle, VGroup, Group, Mobject, VMobject
>>> s, r, m, v = Square(), Rectangle(), Mobject(), VMobject()
>>> vg = VGroup(s, r)
>>> gr = Group(vg, m, v)
>>> gr.family_members_with_points()
[Square, Rectangle]
See also

get_family()

flip(axis: Vector3DLike = array([0., 1., 0.]), *, about_point: Point3DLike | None = None, about_edge: Vector3DLike | None = None) → Self

Flips/Mirrors an mobject about its center.

Examples
class FlipExample(Scene):
    def construct(self):
        s= Line(LEFT, RIGHT+UP).shift(4*LEFT)
        self.add(s)
        s2= s.copy().flip()
        self.add(s2)
generate_points() → Self

Initializes points and therefore the shape.

Gets called upon creation. This is an empty method that can be implemented by subclasses.

get_all_points() → Point3D_Array

Return all points from this mobject and all submobjects.

May contain duplicates; the order is in a depth-first (pre-order) traversal of the submobjects.

get_bottom() → Point3D

Get bottom Point3Ds of a box bounding the Mobject

get_center() → Point3D

Get center Point3Ds

get_color() → ManimColor

Returns the color of the Mobject

Examples
>>> from manim import Square, RED
>>> Square(color=RED).get_color() == RED
True
get_coord(dim: int, direction: Vector3DLike = array([0., 0., 0.])) → float

Meant to generalize get_x, get_y and get_z

get_corner(direction: Vector3DLike) → Point3D

Get corner Point3Ds for certain direction.

get_critical_point(direction: Vector3DLike) → Point3D

Picture a box bounding the Mobject. Such a box has 9 'critical points': 4 corners, 4 edge center, the center. This returns one of them, along the given direction.

sample = Arc(start_angle=PI / 7, angle=PI / 5)

# These are all equivalent
max_y_1 = sample.get_top()[1]
max_y_2 = sample.get_critical_point(UP)[1]
max_y_3 = sample.get_extremum_along_dim(dim=1, key=1)
get_edge_center(direction: Vector3DLike) → Point3D

Get edge Point3Ds for certain direction.

get_end() → Point3D

Returns the point, where the stroke that surrounds the Mobject ends.

get_family(recurse: bool = True) → list[Mobject]

Lists all mobjects in the hierarchy (family) of the given mobject, including the mobject itself and all its submobjects recursively.

Parameters
recurse

Just for consistency with get_family method in OpenGLMobject.

Returns
list[Mobject]

A list of mobjects in the family of the given mobject.

Examples
>>> from manim import Square, Rectangle, VGroup, Group, Mobject, VMobject
>>> s, r, m, v = Square(), Rectangle(), Mobject(), VMobject()
>>> vg = VGroup(s, r)
>>> gr = Group(vg, m, v)
>>> gr.get_family()
[Group, VGroup(Square, Rectangle), Square, Rectangle, Mobject, VMobject]
See also

family_members_with_points(), align_data()

get_left() → Point3D

Get left Point3Ds of a box bounding the Mobject

get_merged_array(array_attr: str) → ndarray

Return all of a given attribute from this mobject and all submobjects.

May contain duplicates; the order is in a depth-first (pre-order) traversal of the submobjects.

get_midpoint() → Point3D

Get Point3Ds of the middle of the path that forms the Mobject.

Examples
class AngleMidPoint(Scene):
    def construct(self):
        line1 = Line(ORIGIN, 2*RIGHT)
        line2 = Line(ORIGIN, 2*RIGHT).rotate_about_origin(80*DEGREES)

        a = Angle(line1, line2, radius=1.5, other_angle=False)
        d = Dot(a.get_midpoint()).set_color(RED)

        self.add(line1, line2, a, d)
        self.wait()
static get_mobject_type_class() → type[Mobject]

Return the base class of this mobject type.

get_nadir() → Point3D

Get nadir (opposite the zenith) Point3Ds of a box bounding a 3D Mobject.

get_point_mobject(center: Point3DLike | None = None) → Point

The simplest Mobject to be transformed to or from self. Should by a point of the appropriate type

get_right() → Point3D

Get right Point3Ds of a box bounding the Mobject

get_start() → Point3D

Returns the point, where the stroke that surrounds the Mobject starts.

get_start_and_end() → tuple[Point3D, Point3D]

Returns starting and ending point of a stroke as a tuple.

get_time_based_updaters() → list[Callable[[Mobject, float], object]]

Return all updaters using the dt parameter.

The updaters use this parameter as the input for difference in time.

Returns
List[Callable]

The list of time based updaters.

See Also

get_updaters() has_time_based_updater()

get_top() → Point3D

Get top Point3Ds of a box bounding the Mobject

get_updaters() → list[Callable[[Mobject], object] | Callable[[Mobject, float], object]]

Return all updaters.

Returns
List[Callable]

The list of updaters.

See Also

add_updater() get_time_based_updaters()

get_x(direction: Vector3DLike = array([0., 0., 0.])) → float

Returns x Point3D of the center of the Mobject as float

get_y(direction: Vector3DLike = array([0., 0., 0.])) → float

Returns y Point3D of the center of the Mobject as float

get_z(direction: Vector3DLike = array([0., 0., 0.])) → float

Returns z Point3D of the center of the Mobject as float

get_zenith() → Point3D

Get zenith Point3Ds of a box bounding a 3D Mobject.

has_no_points() → bool

Check if Mobject does not contains points.

has_points() → bool

Check if Mobject contains points.

has_time_based_updater() → bool

Test if self has a time based updater.

Returns
bool

True if at least one updater uses the dt parameter, False otherwise.

See Also

get_time_based_updaters()

property height: float

The height of the mobject.

Returns

float

Examples
class HeightExample(Scene):
    def construct(self):
        decimal = DecimalNumber().to_edge(UP)
        rect = Rectangle(color=BLUE)
        rect_copy = rect.copy().set_stroke(GRAY, opacity=0.5)

        decimal.add_updater(lambda d: d.set_value(rect.height))

        self.add(rect_copy, rect, decimal)
        self.play(rect.animate.set(height=5))
        self.wait()
See also

length_over_dim()

init_colors(propagate_colors: bool = True) → Self

Initializes the colors.

Gets called upon creation. This is an empty method that can be implemented by subclasses.

insert(index: int, mobject: Mobject) → Self

Inserts a mobject at a specific position into self.submobjects

Effectively just calls self.submobjects.insert(index, mobject), where self.submobjects is a list.

Highly adapted from Mobject.add.

Parameters
index

The index at which

mobject

The mobject to be inserted.

interpolate(mobject1: Mobject, mobject2: Mobject, alpha: float, path_func: PathFuncType = <function interpolate>) → Self

Turns this Mobject into an interpolation between mobject1 and mobject2.

The interpolation is applied to the points and color of the mobject.

Parameters
mobject1

The starting Mobject.

mobject2

The target Mobject.

alpha

Interpolation factor between 0 (at mobject1) and 1 (at mobject2).

path_func

The function defining the interpolation path. Defaults to a straight path.

Returns
Mobject

self

备注

  • Both mobjects must have the same number of points. If not, this will raise an error. Use align_points() to match point counts beforehand if needed.

  • This method is used internally by the Transform animation to interpolate between two mobjects during a transformation.

Examples
class InterpolateExample(Scene):
    def construct(self):
        # No need for point alignment:
        dotL = Dot(color=DARK_GREY).to_edge(LEFT)
        dotR = Dot(color=YELLOW).scale(10).to_edge(RIGHT)
        dotMid1 = VMobject().interpolate(dotL, dotR, alpha=0.1)
        dotMid2 = VMobject().interpolate(dotL, dotR, alpha=0.25)
        dotMid3 = VMobject().interpolate(dotL, dotR, alpha=0.5)
        dotMid4 = VMobject().interpolate(dotL, dotR, alpha=0.75)
        dots = VGroup(dotL, dotR, dotMid1, dotMid2, dotMid3, dotMid4)

        # Needs point alignment:
        line = Line(ORIGIN, UP).to_edge(LEFT)
        sq = Square(color=RED, fill_opacity=1, stroke_color=BLUE).to_edge(RIGHT)
        line.align_points(sq)
        mid1 = VMobject().interpolate(line, sq, alpha=0.1)
        mid2 = VMobject().interpolate(line, sq, alpha=0.25)
        mid3 = VMobject().interpolate(line, sq, alpha=0.5)
        mid4 = VMobject().interpolate(line, sq, alpha=0.75)
        linesquares = VGroup(line, sq, mid1, mid2, mid3, mid4)

        self.add(VGroup(dots, linesquares).arrange(DOWN, buff=1))
See also

Transform, align_points(), interpolate_color()

invert(recursive: bool = False) → Self

Inverts the list of submobjects.

Parameters
recursive

If True, all submobject lists of this mobject's family are inverted.

Examples
class InvertSumobjectsExample(Scene):
    def construct(self):
        s = VGroup(*[Dot().shift(i*0.1*RIGHT) for i in range(-20,20)])
        s2 = s.copy()
        s2.invert()
        s2.shift(DOWN)
        self.play(Write(s), Write(s2))
length_over_dim(dim: int) → float

Measure the length of an Mobject in a certain direction.

match_color(mobject: Mobject) → Self

Match the color with the color of another Mobject.

match_coord(mobject: Mobject, dim: int, direction: Vector3DLike = array([0., 0., 0.])) → Self

Match the Point3Ds with the Point3Ds of another Mobject.

match_depth(mobject: Mobject, **kwargs: Any) → Self

Match the depth with the depth of another Mobject.

match_dim_size(mobject: Mobject, dim: int, **kwargs: Any) → Self

Match the specified dimension with the dimension of another Mobject.

match_height(mobject: Mobject, **kwargs: Any) → Self

Match the height with the height of another Mobject.

match_points(mobject: Mobject, copy_submobjects: bool = True) → Self

Edit points, positions, and submobjects to be identical to another Mobject, while keeping the style unchanged.

Examples
class MatchPointsScene(Scene):
    def construct(self):
        circ = Circle(fill_color=RED, fill_opacity=0.8)
        square = Square(fill_color=BLUE, fill_opacity=0.2)
        self.add(circ)
        self.wait(0.5)
        self.play(circ.animate.match_points(square))
        self.wait(0.5)
match_updaters(mobject: Mobject) → Self

Match the updaters of the given mobject.

Parameters
mobject

The mobject whose updaters get matched.

Returns
Mobject

self

Note

All updaters from submobjects are removed, but only updaters of the given mobject are matched, not those of it's submobjects.

See also

add_updater() clear_updaters()

match_width(mobject: Mobject, **kwargs: Any) → Self

Match the width with the width of another Mobject.

match_x(mobject: Mobject, direction: Vector3DLike = array([0., 0., 0.])) → Self

Match x coord. to the x coord. of another Mobject.

match_y(mobject: Mobject, direction: Vector3DLike = array([0., 0., 0.])) → Self

Match y coord. to the x coord. of another Mobject.

match_z(mobject: Mobject, direction: Vector3DLike = array([0., 0., 0.])) → Self

Match z coord. to the x coord. of another Mobject.

move_to(point_or_mobject: Point3DLike | Mobject, aligned_edge: Vector3DLike = array([0., 0., 0.]), coor_mask: Vector3DLike = array([1, 1, 1])) → Self

Move center of the Mobject to certain Point3D.

next_to(mobject_or_point: Mobject | Point3DLike, direction: Vector3DLike = array([1., 0., 0.]), buff: float = 0.25, aligned_edge: Vector3DLike = array([0., 0., 0.]), submobject_to_align: Mobject | None = None, index_of_submobject_to_align: int | None = None, coor_mask: Vector3DLike = array([1, 1, 1])) → Self

Move this Mobject next to another's Mobject or Point3D.

Examples
class GeometricShapes(Scene):
    def construct(self):
        d = Dot()
        c = Circle()
        s = Square()
        t = Triangle()
        d.next_to(c, RIGHT)
        s.next_to(c, LEFT)
        t.next_to(c, DOWN)
        self.add(d, c, s, t)
null_point_align(mobject: Mobject) → Self

If a Mobject with points is being aligned to one without, treat both as groups, and push the one with points into its own submobjects list.

Returns
Mobject

self

reduce_across_dimension(reduce_func: Callable[[Iterable[float]], float], dim: int) → float | None

Find the min or max value from a dimension across all points in this Mobject and its submobjects. This allows for using length_over_dim() to calculate its length over a dimension, i.e. its height, width or depth. If this Mobject is empty, return None, since this Mobject should not be taken into account when calculating lengths.

Parameters
reduce_func

The reducer function to use in order to calculate a value over a dimension.

dim

The dimension to use. It should be 0, 1 or 2, representing the X, Y or Z coordinate, respectively.

Returns
float | None

The min or max value over the dimension specified by dim, or None if this Mobject is empty.

remove(*mobjects: Mobject) → Self

Remove submobjects.

The mobjects are removed from submobjects, if they exist.

Subclasses of mobject may implement - and -= dunder methods.

Parameters
mobjects

The mobjects to remove.

Returns
Mobject

self

See Also

add()

remove_updater(update_function: _Updater) → Self

Remove an updater.

If the same updater is applied multiple times, every instance gets removed.

Parameters
update_function

The update function to be removed.

Returns
Mobject

self

See also

clear_updaters() add_updater() get_updaters()

repeat(count: int) → Self

This can make transition animations nicer

reset_points() → Self

Sets points to be an empty array.

restore() → Self

Restores the state that was previously saved with save_state().

resume_updating(recursive: bool = True) → Self

Enable updating from updaters and animations.

Parameters
recursive

Whether to recursively enable updating on all submobjects.

Returns
Mobject

self

See also

suspend_updating() add_updater()

rotate(angle: float, axis: Vector3DLike = array([0., 0., 1.]), *, about_point: Point3DLike | None = None, about_edge: Vector3DLike | None = None, **kwargs: Any) → Self

Rotates the Mobject around a specified axis and point.

Parameters
angle

The angle of rotation in radians. Predefined constants such as DEGREES can also be used to specify the angle in degrees.

axis

The rotation axis (see Rotating for more).

about_point

The point about which the mobject rotates. If None, rotation occurs around the center of the mobject.

about_edge

The edge about which to apply the scaling.

Returns
Mobject

self (for method chaining)

备注

To animate a rotation, use Rotating or Rotate instead of .animate.rotate(...). The .animate.rotate(...) syntax only applies a transformation from the initial state to the final rotated state (interpolation between the two states), without showing proper rotational motion based on the angle (from 0 to the given angle).

Examples
class RotateMethodExample(Scene):
    def construct(self):
        circle = Circle(radius=1, color=BLUE)
        line = Line(start=ORIGIN, end=RIGHT)
        arrow1 = Arrow(start=ORIGIN, end=RIGHT, buff=0, color=GOLD)
        group1 = VGroup(circle, line, arrow1)

        group2 = group1.copy()
        arrow2 = group2[2]
        arrow2.rotate(angle=PI / 4, about_point=arrow2.get_start())

        group3 = group1.copy()
        arrow3 = group3[2]
        arrow3.rotate(angle=120 * DEGREES, about_point=arrow3.get_start())

        self.add(VGroup(group1, group2, group3).arrange(RIGHT, buff=1))
See also

Rotating, Rotate, animate, apply_points_function_about_point()

rotate_about_origin(angle: float, axis: Vector3DLike = array([0., 0., 1.])) → Self

Rotates the Mobject about the ORIGIN, which is at [0,0,0].

save_image(name: str | None = None) → None

Saves an image of only this Mobject at its position to a png file.

save_state() → Self

Save the current state (position, color & size). Can be restored with restore().

scale(scale_factor: float, *, about_point: Point3DLike | None = None, about_edge: Vector3DLike | None = None) → Self

Scale the size by a factor.

Default behavior is to scale about the center of the mobject.

Parameters
scale_factor

The scaling factor \(\alpha\). If \(0 < |\alpha| < 1\), the mobject will shrink, and for \(|\alpha| > 1\) it will grow. Furthermore, if \(\alpha < 0\), the mobject is also flipped.

about_point

The point about which to apply the scaling.

about_edge

The edge about which to apply the scaling.

Returns
Mobject

self

Examples
class MobjectScaleExample(Scene):
    def construct(self):
        f1 = Text("F")
        f2 = Text("F").scale(2)
        f3 = Text("F").scale(0.5)
        f4 = Text("F").scale(-1)

        vgroup = VGroup(f1, f2, f3, f4).arrange(6 * RIGHT)
        self.add(vgroup)
See also

move_to()

scale_to_fit_depth(depth: float, **kwargs: Any) → Self

Scales the Mobject to fit a depth while keeping width/height proportional.

scale_to_fit_height(height: float, **kwargs: Any) → Self

Scales the Mobject to fit a height while keeping width/depth proportional.

Returns
Mobject

self

Examples
>>> from manim import *
>>> sq = Square()
>>> sq.width
np.float64(2.0)
>>> sq.scale_to_fit_height(5)
Square
>>> sq.height
np.float64(5.0)
>>> sq.width
np.float64(5.0)
scale_to_fit_width(width: float, **kwargs: Any) → Self

Scales the Mobject to fit a width while keeping height/depth proportional.

Returns
Mobject

self

Examples
>>> from manim import *
>>> sq = Square()
>>> sq.height
np.float64(2.0)
>>> sq.scale_to_fit_width(5)
Square
>>> sq.width
np.float64(5.0)
>>> sq.height
np.float64(5.0)
set(**kwargs: Any) → Self

Sets attributes.

I.e. my_mobject.set(foo=1) applies my_mobject.foo = 1.

This is a convenience to be used along with animate to animate setting attributes.

In addition to this method, there is a compatibility layer that allows get_* and set_* methods to get and set generic attributes. For instance:

>>> mob = Mobject()
>>> mob.set_foo(0)
Mobject
>>> mob.get_foo()
0
>>> mob.foo
0

This compatibility layer does not interfere with any get_* or set_* methods that are explicitly defined.

警告

This compatibility layer is for backwards compatibility and is not guaranteed to stay around. Where applicable, please prefer getting/setting attributes normally or with the set() method.

Parameters
**kwargs

The attributes and corresponding values to set.

Returns
Mobject

self

Examples
>>> mob = Mobject()
>>> mob.set(foo=0)
Mobject
>>> mob.foo
0
set_color(color: ParsableManimColor = ManimColor('#FFFF00'), alpha: Any = None, family: bool = True) → Self

Condition is function which takes in one arguments, (x, y, z). Here it just recurses to submobjects, but in subclasses this should be further implemented based on the the inner workings of color

set_color_by_gradient(*colors: ParsableManimColor) → Self
Parameters
colors

The colors to use for the gradient. Use like set_color_by_gradient(RED, BLUE, GREEN).

self.color = ManimColor.parse(color) return self

classmethod set_default(**kwargs: Any) → None

Sets the default values of keyword arguments.

If this method is called without any additional keyword arguments, the original default values of the initialization method of this class are restored.

Parameters
kwargs

Passing any keyword argument will update the default values of the keyword arguments of the initialization function of this class.

Examples
>>> from manim import Square, GREEN
>>> Square.set_default(color=GREEN, fill_opacity=0.25)
>>> s = Square(); s.color, s.fill_opacity
(ManimColor('#83C167'), 0.25)
>>> Square.set_default()
>>> s = Square(); s.color, s.fill_opacity
(ManimColor('#FFFFFF'), 0.0)
config.background_color = WHITE

class ChangedDefaultTextcolor(Scene):
    def construct(self):
        Text.set_default(color=BLACK)
        self.add(Text("Changing default values is easy!"))

        # we revert the colour back to the default to prevent a bug in the docs.
        Text.set_default(color=WHITE)
set_x(x: float, direction: Vector3DLike = array([0., 0., 0.])) → Self

Set x value of the center of the Mobject (int or float)

set_y(y: float, direction: Vector3DLike = array([0., 0., 0.])) → Self

Set y value of the center of the Mobject (int or float)

set_z(z: float, direction: Vector3DLike = array([0., 0., 0.])) → Self

Set z value of the center of the Mobject (int or float)

set_z_index(z_index_value: float, family: bool = True) → Self

Sets the Mobject's z_index to the value specified in z_index_value.

Parameters
z_index_value

The new value of z_index set.

family

If True, the z_index value of all submobjects is also set.

Returns
Mobject

The Mobject itself, after z_index is set. For chaining purposes. (Returns self.)

Examples
class SetZIndex(Scene):
    def construct(self):
        text = Text('z_index = 3', color = PURE_RED).shift(UP).set_z_index(3)
        square = Square(2, fill_opacity=1).set_z_index(2)
        tex = Tex(r'zIndex = 1', color = PURE_BLUE).shift(DOWN).set_z_index(1)
        circle = Circle(radius = 1.7, color = GREEN, fill_opacity = 1) # z_index = 0

        # Displaying order is now defined by z_index values
        self.add(text)
        self.add(square)
        self.add(tex)
        self.add(circle)
set_z_index_by_z_Point3D() → Self

Sets the Mobject's z Point3D to the value of z_index.

Returns
Mobject

The Mobject itself, after z_index is set. (Returns self.)

shift(*vectors: Vector3DLike) → Self

Shift by the given vectors.

Parameters
vectors

Vectors to shift by. If multiple vectors are given, they are added together.

Returns
Mobject

self

See also

move_to()

shuffle(recursive: bool = False) → Self

Shuffles the list of submobjects.

shuffle_submobjects(*args: Any, **kwargs: Any) → Self

Shuffles the order of submobjects

Examples
class ShuffleSubmobjectsExample(Scene):
    def construct(self):
        s= VGroup(*[Dot().shift(i*0.1*RIGHT) for i in range(-20,20)])
        s2= s.copy()
        s2.shuffle_submobjects()
        s2.shift(DOWN)
        self.play(Write(s), Write(s2))
sort(point_to_num_func: Callable[[Point3DLike], float] = <function Mobject.<lambda>>, submob_func: Callable[[Mobject], Any] | None = None) → Self

Sorts the list of submobjects by a function defined by submob_func.

sort_submobjects(*args: Any, **kwargs: Any) → Self

Sort the submobjects

stretch_to_fit_depth(depth: float, **kwargs: Any) → Self

Stretches the Mobject to fit a depth, not keeping width/height proportional.

stretch_to_fit_height(height: float, **kwargs: Any) → Self

Stretches the Mobject to fit a height, not keeping width/depth proportional.

Returns
Mobject

self

Examples
>>> from manim import *
>>> sq = Square()
>>> sq.width
np.float64(2.0)
>>> sq.stretch_to_fit_height(5)
Square
>>> sq.height
np.float64(5.0)
>>> sq.width
np.float64(2.0)
stretch_to_fit_width(width: float, **kwargs: Any) → Self

Stretches the Mobject to fit a width, not keeping height/depth proportional.

Returns
Mobject

self

Examples
>>> from manim import *
>>> sq = Square()
>>> sq.height
np.float64(2.0)
>>> sq.stretch_to_fit_width(5)
Square
>>> sq.width
np.float64(5.0)
>>> sq.height
np.float64(2.0)
suspend_updating(recursive: bool = True) → Self

Disable updating from updaters and animations.

Parameters
recursive

Whether to recursively suspend updating on all submobjects.

Returns
Mobject

self

See also

resume_updating() add_updater()

to_corner(corner: Vector3DLike = array([-1., -1., 0.]), buff: float = 0.5) → Self

Moves this Mobject to the given corner of the screen.

Returns
Mobject

The newly positioned mobject.

Examples
class ToCornerExample(Scene):
    def construct(self):
        c = Circle()
        c.to_corner(UR)
        t = Tex("To the corner!")
        t2 = MathTex("x^3").shift(DOWN)
        self.add(c,t,t2)
        t.to_corner(DL, buff=0)
        t2.to_corner(UL, buff=1.5)
to_edge(edge: Vector3DLike = array([-1., 0., 0.]), buff: float = 0.5) → Self

Moves this Mobject to the given edge of the screen, without affecting its position in the other dimension.

Returns
Mobject

The newly positioned mobject.

Examples
class ToEdgeExample(Scene):
    def construct(self):
        tex_top = Tex("I am at the top!")
        tex_top.to_edge(UP)
        tex_side = Tex("I am moving to the side!")
        c = Circle().shift(2*DOWN)
        self.add(tex_top, tex_side, c)
        tex_side.to_edge(LEFT)
        c.to_edge(RIGHT, buff=0)
update(dt: float = 0, recursive: bool = True) → Self

Apply all updaters.

Does nothing if updating is suspended.

Parameters
dt

The parameter dt to pass to the update functions. Usually this is the time in seconds since the last call of update.

recursive

Whether to recursively update all submobjects.

Returns
Mobject

self

See Also

add_updater() get_updaters()

property width: float

The width of the mobject.

Returns

float

Examples
class WidthExample(Scene):
    def construct(self):
        decimal = DecimalNumber().to_edge(UP)
        rect = Rectangle(color=BLUE)
        rect_copy = rect.copy().set_stroke(GRAY, opacity=0.5)

        decimal.add_updater(lambda d: d.set_value(rect.width))

        self.add(rect_copy, rect, decimal)
        self.play(rect.animate.set(width=7))
        self.wait()
See also

length_over_dim()

MobjectMatrix

元素为任意 Mobject 的矩阵:把图形本身排成矩阵布局展示。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Mobject" -> "VMobject"; "VMobject" -> "Matrix"; "Matrix" -> "MobjectMatrix"; }

参数

matrix

—,Iterable[Iterable[Any]]

element_to_mobject

<function MobjectMatrix.<la…

API 文档

class manim.MobjectMatrix(matrix: ~collections.abc.Iterable[~collections.abc.Iterable[~typing.Any]], element_to_mobject: type[~manim.mobject.types.vectorized_mobject.VMobject] | ~collections.abc.Callable[[...], ~manim.mobject.types.vectorized_mobject.VMobject] = <function MobjectMatrix.<lambda>>, **kwargs: ~typing.Any)

基类:Matrix

A mobject that displays a matrix of mobject entries on the screen.

Examples

class MobjectMatrixExample(Scene):
    def construct(self):
        a = Circle().scale(0.3)
        b = Square().scale(0.3)
        c = MathTex("\\pi").scale(2)
        d = Star().scale(0.3)
        m0 = MobjectMatrix([[a, b], [c, d]])
        self.add(m0)

MobjectTable

单元格为任意 Mobject 的通用表格,最自由的表格形态。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Mobject" -> "VMobject"; "VMobject" -> "VGroup"; "VGroup" -> "Table"; "Table" -> "MobjectTable"; }

参数

table

—

element_to_mobject

<function MobjectTable.<lam…

快速上手

t = MobjectTable([[dot, circle], [square, star]])

API 文档

class manim.MobjectTable(table: ~collections.abc.Iterable[~collections.abc.Iterable[~manim.mobject.types.vectorized_mobject.VMobject]], element_to_mobject: ~collections.abc.Callable[[~manim.mobject.types.vectorized_mobject.VMobject], ~manim.mobject.types.vectorized_mobject.VMobject] | type[~manim.mobject.types.vectorized_mobject.VMobject] = <function MobjectTable.<lambda>>, **kwargs: ~typing.Any)

基类:Table

A specialized Table mobject for use with Mobject.

Examples

class MobjectTableExample(Scene):
    def construct(self):
        cross = VGroup(
            Line(UP + LEFT, DOWN + RIGHT),
            Line(UP + RIGHT, DOWN + LEFT),
        )
        a = Circle().set_color(RED).scale(0.5)
        b = cross.set_color(BLUE).scale(0.5)
        t0 = MobjectTable(
            [[a.copy(),b.copy(),a.copy()],
            [b.copy(),a.copy(),a.copy()],
            [a.copy(),b.copy(),b.copy()]]
        )
        line = Line(
            t0.get_corner(DL), t0.get_corner(UR)
        ).set_color(RED)
        self.add(t0, line)

ScreenRectangle

按 16:9 屏幕比例裁出的矩形,适合作画中画框或参考取景框。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Mobject" -> "VMobject"; "VMobject" -> "Polygram"; "Polygram" -> "Polygon"; "Polygon" -> "Rectangle"; "Rectangle" -> "ScreenRectangle"; }

参数

aspect_ratio

1.7777777777777777,float

height

4,float

快速上手

frame = ScreenRectangle(height=3)

API 文档

class manim.ScreenRectangle(aspect_ratio: float = 1.7777777777777777, height: float = 4, **kwargs: Any)

基类:Rectangle

property aspect_ratio: float

The aspect ratio.

When set, the width is stretched to accommodate the new aspect ratio.

StreamLines

沿向量场绘出流线族(积分曲线),比 ArrowVectorField 更能表现场的整体走势。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Mobject" -> "VMobject"; "VMobject" -> "VGroup"; "VGroup" -> "VectorField"; "VectorField" -> "StreamLines"; }

参数

func

—

color

None

color_scheme

None

min_color_scheme_value

0,float

max_color_scheme_value

2,float

colors

[ManimColor('#236B8E'), Man…

x_range

None,Sequence[float]

y_range

None,Sequence[float]

z_range

None,Sequence[float]

three_dimensions

False,bool

noise_factor

None,float | None

n_repeats

1

dt

0.05

virtual_time

3

max_anchors_per_line

100

padding

3

stroke_width

1

opacity

1

快速上手

lines = StreamLines(lambda p: np.array([-p[1], p[0], 0]))

API 文档

class manim.StreamLines(func: Callable[[ndarray], ndarray], color: ManimColor | int | str | NDArray[int64] | tuple[int, int, int] | NDArray[float64] | tuple[float, float, float] | tuple[int, int, int, int] | tuple[float, float, float, float] | None = None, color_scheme: Callable[[ndarray], float] | None = None, min_color_scheme_value: float = 0, max_color_scheme_value: float = 2, colors: Sequence[ManimColor | int | str | NDArray[int64] | tuple[int, int, int] | NDArray[float64] | tuple[float, float, float] | tuple[int, int, int, int] | tuple[float, float, float, float]] = [ManimColor('#236B8E'), ManimColor('#83C167'), ManimColor('#F7D96F'), ManimColor('#FC6255')], x_range: Sequence[float] = None, y_range: Sequence[float] = None, z_range: Sequence[float] = None, three_dimensions: bool = False, noise_factor: float | None = None, n_repeats=1, dt=0.05, virtual_time=3, max_anchors_per_line=100, padding=3, stroke_width=1, opacity=1, **kwargs)

基类:VectorField

StreamLines represent the flow of a VectorField using the trace of moving agents.

Vector fields are always based on a function defining the vector at every position. The values of this functions is displayed by moving many agents along the vector field and showing their trace.

Parameters

func

The function defining the rate of change at every position of the vector field.

color

The color of the vector field. If set, position-specific coloring is disabled.

color_scheme

A function mapping a vector to a single value. This value gives the position in the color gradient defined using min_color_scheme_value, max_color_scheme_value and colors.

min_color_scheme_value

The value of the color_scheme function to be mapped to the first color in colors. Lower values also result in the first color of the gradient.

max_color_scheme_value

The value of the color_scheme function to be mapped to the last color in colors. Higher values also result in the last color of the gradient.

colors

The colors defining the color gradient of the vector field.

x_range

A sequence of x_min, x_max, delta_x

y_range

A sequence of y_min, y_max, delta_y

z_range

A sequence of z_min, z_max, delta_z

three_dimensions

Enables three_dimensions. Default set to False, automatically turns True if z_range is not None.

noise_factor

The amount by which the starting position of each agent is altered along each axis. Defaults to delta_y / 2 if not defined.

n_repeats

The number of agents generated at each starting point.

dt

The factor by which the distance an agent moves per step is stretched. Lower values result in a better approximation of the trajectories in the vector field.

virtual_time

The time the agents get to move in the vector field. Higher values therefore result in longer stream lines. However, this whole time gets simulated upon creation.

max_anchors_per_line

The maximum number of anchors per line. Lines with more anchors get reduced in complexity, not in length.

padding

The distance agents can move out of the generation area before being terminated.

stroke_width

The stroke with of the stream lines.

opacity

The opacity of the stream lines.

Examples

class BasicUsage(Scene):
    def construct(self):
        func = lambda pos: ((pos[0] * UR + pos[1] * LEFT) - pos) / 3
        self.add(StreamLines(func))
class SpawningAndFlowingArea(Scene):
    def construct(self):
        func = lambda pos: np.sin(pos[0]) * UR + np.cos(pos[1]) * LEFT + pos / 5
        stream_lines = StreamLines(
            func, x_range=[-3, 3, 0.2], y_range=[-2, 2, 0.2], padding=1
        )

        spawning_area = Rectangle(width=6, height=4)
        flowing_area = Rectangle(width=8, height=6)
        labels = [Tex("Spawning Area"), Tex("Flowing Area").shift(DOWN * 2.5)]
        for lbl in labels:
            lbl.add_background_rectangle(opacity=0.6, buff=0.05)

        self.add(stream_lines, spawning_area, flowing_area, *labels)
create(lag_ratio: float | None = None, run_time: Callable[[float], float] | None = None, **kwargs) → AnimationGroup

The creation animation of the stream lines.

The stream lines appear in random order.

Parameters
lag_ratio

The lag ratio of the animation. If undefined, it will be selected so that the total animation length is 1.5 times the run time of each stream line creation.

run_time

The run time of every single stream line creation. The runtime of the whole animation might be longer due to the lag_ratio. If undefined, the virtual time of the stream lines is used as run time.

Returns
AnimationGroup

The creation animation of the stream lines.

Examples
class StreamLineCreation(Scene):
    def construct(self):
        func = lambda pos: (pos[0] * UR + pos[1] * LEFT) - pos
        stream_lines = StreamLines(
            func,
            color=YELLOW,
            x_range=[-7, 7, 1],
            y_range=[-4, 4, 1],
            stroke_width=3,
            virtual_time=1,  # use shorter lines
            max_anchors_per_line=5,  # better performance with fewer anchors
        )
        self.play(stream_lines.create())  # uses virtual_time as run_time
        self.wait()
end_animation() → AnimationGroup

End the stream line animation smoothly.

Returns an animation resulting in fully displayed stream lines without a noticeable cut.

Returns
AnimationGroup

The animation fading out the running stream animation.

Raises
ValueError

if no stream line animation is running

Examples
class EndAnimation(Scene):
    def construct(self):
        func = lambda pos: np.sin(pos[0] / 2) * UR + np.cos(pos[1] / 2) * LEFT
        stream_lines = StreamLines(
            func, stroke_width=3, max_anchors_per_line=5, virtual_time=1, color=BLUE
        )
        self.add(stream_lines)
        stream_lines.start_animation(warm_up=False, flow_speed=1.5, time_width=0.5)
        self.wait(1)
        self.play(stream_lines.end_animation())
start_animation(warm_up: bool = True, flow_speed: float = 1, time_width: float = 0.3, rate_func: ~collections.abc.Callable[[float], float] = <function linear>, line_animation_class: type[~manim.animation.indication.ShowPassingFlash] = <class 'manim.animation.indication.ShowPassingFlash'>, **kwargs) → Self

Animates the stream lines using an updater.

The stream lines will continuously flow

Parameters
warm_up

If True the animation is initialized line by line. Otherwise it starts with all lines shown.

flow_speed

At flow_speed=1 the distance the flow moves per second is equal to the magnitude of the vector field along its path. The speed value scales the speed of this flow.

time_width

The proportion of the stream line shown while being animated

rate_func

The rate function of each stream line flashing

line_animation_class

The animation class being used

Examples
class ContinuousMotion(Scene):
    def construct(self):
        func = lambda pos: np.sin(pos[0] / 2) * UR + np.cos(pos[1] / 2) * LEFT
        stream_lines = StreamLines(func, stroke_width=3, max_anchors_per_line=30)
        self.add(stream_lines)
        stream_lines.start_animation(warm_up=False, flow_speed=1.5)
        self.wait(stream_lines.virtual_time / stream_lines.flow_speed)

Table

表格基类:字符串单元格 + 行列标签 + 边框样式,add_highlighted_cell 可做聚光单元格。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Mobject" -> "VMobject"; "VMobject" -> "VGroup"; "VGroup" -> "Table"; }

参数

table

—

row_labels

None

col_labels

None

top_left_entry

None,VMobject | None

v_buff

0.8,float

h_buff

1.3,float

include_outer_lines

False,bool

include_inner_lines

True,bool

add_background_rectangles_to_entries

False,bool

entries_background_color

ManimColor('#000000'),ParsableManimColor

include_background_rectangle

False,bool

background_rectangle_color

ManimColor('#000000'),ParsableManimColor

element_to_mobject

<class 'manim.mobject.text.…

element_to_mobject_config

{},dict

arrange_in_grid_config

{},dict

line_config

{},dict

快速上手

t = Table([["a", "b"], ["c", "d"]], row_labels=[1, 2])

API 文档

class manim.Table(table: ~collections.abc.Iterable[~collections.abc.Iterable[float | str | ~manim.mobject.types.vectorized_mobject.VMobject]], row_labels: ~collections.abc.Iterable[~manim.mobject.types.vectorized_mobject.VMobject] | None = None, col_labels: ~collections.abc.Iterable[~manim.mobject.types.vectorized_mobject.VMobject] | None = None, top_left_entry: ~manim.mobject.types.vectorized_mobject.VMobject | None = None, v_buff: float = 0.8, h_buff: float = 1.3, include_outer_lines: bool = False, include_inner_lines: bool = True, add_background_rectangles_to_entries: bool = False, entries_background_color: ~manim.utils.color.core.ManimColor | int | str | ~numpy._typing._array_like.NDArray[~numpy.int64] | tuple[int, int, int] | ~numpy._typing._array_like.NDArray[~numpy.float64] | tuple[float, float, float] | tuple[int, int, int, int] | tuple[float, float, float, float] = ManimColor('#000000'), include_background_rectangle: bool = False, background_rectangle_color: ~manim.utils.color.core.ManimColor | int | str | ~numpy._typing._array_like.NDArray[~numpy.int64] | tuple[int, int, int] | ~numpy._typing._array_like.NDArray[~numpy.float64] | tuple[float, float, float] | tuple[int, int, int, int] | tuple[float, float, float, float] = ManimColor('#000000'), element_to_mobject: ~collections.abc.Callable[[float | str], ~manim.mobject.types.vectorized_mobject.VMobject] | ~collections.abc.Callable[[~manim.mobject.types.vectorized_mobject.VMobject], ~manim.mobject.types.vectorized_mobject.VMobject] | ~collections.abc.Callable[[float | str | ~manim.mobject.types.vectorized_mobject.VMobject], ~manim.mobject.types.vectorized_mobject.VMobject] | type[~manim.mobject.types.vectorized_mobject.VMobject] = <class 'manim.mobject.text.text_mobject.Paragraph'>, element_to_mobject_config: dict = {}, arrange_in_grid_config: dict = {}, line_config: dict = {}, **kwargs: ~typing.Any)

基类:VGroup

A mobject that displays a table on the screen.

Parameters

table

A non-empty, finite iterable of equally sized iterables. The content has to be valid input for the callable set in element_to_mobject.

row_labels

An iterable of VMobject representing the labels of each row.

col_labels

An iterable of VMobject representing the labels of each column.

top_left_entry

The top-left entry of the table, can only be specified if row and column labels are given.

v_buff

Vertical buffer passed to arrange_in_grid(), by default 0.8.

h_buff

Horizontal buffer passed to arrange_in_grid(), by default 1.3.

include_outer_lines

True if the table should include outer lines, by default False.

include_inner_lines

True if the table should include inner lines, by default True.

add_background_rectangles_to_entries

True if background rectangles should be added to entries, by default False.

entries_background_color

Background color of entries if add_background_rectangles_to_entries is True.

include_background_rectangle

True if the table should have a background rectangle, by default False.

background_rectangle_color

Background color of table if include_background_rectangle is True.

element_to_mobject

The Mobject class applied to the table entries. by default Paragraph. For common choices, see text_mobject/tex_mobject.

element_to_mobject_config

Custom configuration passed to element_to_mobject, by default {}.

arrange_in_grid_config

Dict passed to arrange_in_grid(), customizes the arrangement of the table.

line_config

Dict passed to Line, customizes the lines of the table.

kwargs

Additional arguments to be passed to VGroup.

Examples

class TableExamples(Scene):
    def construct(self):
        t0 = Table(
            [["This", "is a"],
            ["simple", "Table in \\n Manim."]])
        t1 = Table(
            [["This", "is a"],
            ["simple", "Table."]],
            row_labels=[Text("R1"), Text("R2")],
            col_labels=[Text("C1"), Text("C2")])
        t1.add_highlighted_cell((2,2), color=YELLOW)
        t2 = Table(
            [["This", "is a"],
            ["simple", "Table."]],
            row_labels=[Text("R1"), Text("R2")],
            col_labels=[Text("C1"), Text("C2")],
            top_left_entry=Star().scale(0.3),
            include_outer_lines=True,
            arrange_in_grid_config={"cell_alignment": RIGHT})
        t2.add(t2.get_cell((2,2), color=RED))
        t3 = Table(
            [["This", "is a"],
            ["simple", "Table."]],
            row_labels=[Text("R1"), Text("R2")],
            col_labels=[Text("C1"), Text("C2")],
            top_left_entry=Star().scale(0.3),
            include_outer_lines=True,
            line_config={"stroke_width": 1, "color": YELLOW})
        t3.remove(*t3.get_vertical_lines())
        g = Group(
            t0,t1,t2,t3
        ).scale(0.7).arrange_in_grid(buff=1)
        self.add(g)
class BackgroundRectanglesExample(Scene):
    def construct(self):
        background = Rectangle(height=6.5, width=13)
        background.set_fill(opacity=.5)
        background.set_color([TEAL, RED, YELLOW])
        self.add(background)
        t0 = Table(
            [["This", "is a"],
            ["simple", "Table."]],
            add_background_rectangles_to_entries=True)
        t1 = Table(
            [["This", "is a"],
            ["simple", "Table."]],
            include_background_rectangle=True)
        g = Group(t0, t1).scale(0.7).arrange(buff=0.5)
        self.add(g)
add_background_to_entries(color: ManimColor | int | str | NDArray[int64] | tuple[int, int, int] | NDArray[float64] | tuple[float, float, float] | tuple[int, int, int, int] | tuple[float, float, float, float] = ManimColor('#000000')) → Self

Adds a black BackgroundRectangle to each entry of the table.

add_highlighted_cell(pos: Sequence[int] = (1, 1), color: ManimColor | int | str | NDArray[int64] | tuple[int, int, int] | NDArray[float64] | tuple[float, float, float] | tuple[int, int, int, int] | tuple[float, float, float, float] = ManimColor('#FFFF00'), **kwargs: Any) → Self

Highlights one cell at a specific position on the table by adding a BackgroundRectangle.

Parameters
pos

The position of a specific entry on the table. (1,1) being the top left entry of the table.

color

The color used to highlight the cell.

kwargs

Additional arguments to be passed to BackgroundRectangle.

Examples
class AddHighlightedCellExample(Scene):
    def construct(self):
        table = Table(
            [["First", "Second"],
            ["Third","Fourth"]],
            row_labels=[Text("R1"), Text("R2")],
            col_labels=[Text("C1"), Text("C2")])
        table.add_highlighted_cell((2,2), color=GREEN)
        self.add(table)
create(lag_ratio: float = 1, line_animation: ~collections.abc.Callable[[~manim.mobject.types.vectorized_mobject.VMobject | ~manim.mobject.types.vectorized_mobject.VGroup], ~manim.animation.animation.Animation] = <class 'manim.animation.creation.Create'>, label_animation: ~collections.abc.Callable[[~manim.mobject.types.vectorized_mobject.VMobject | ~manim.mobject.types.vectorized_mobject.VGroup], ~manim.animation.animation.Animation] = <class 'manim.animation.creation.Write'>, element_animation: ~collections.abc.Callable[[~manim.mobject.types.vectorized_mobject.VMobject | ~manim.mobject.types.vectorized_mobject.VGroup], ~manim.animation.animation.Animation] = <class 'manim.animation.creation.Create'>, entry_animation: ~collections.abc.Callable[[~manim.mobject.types.vectorized_mobject.VMobject | ~manim.mobject.types.vectorized_mobject.VGroup], ~manim.animation.animation.Animation] = <class 'manim.animation.fading.FadeIn'>, **kwargs: ~typing.Any) → AnimationGroup

Customized create-type function for tables.

Parameters
lag_ratio

The lag ratio of the animation.

line_animation

The animation style of the table lines, see creation for examples.

label_animation

The animation style of the table labels, see creation for examples.

element_animation

The animation style of the table elements, see creation for examples.

entry_animation

The entry animation of the table background, see creation for examples.

kwargs

Further arguments passed to the creation animations.

Returns
AnimationGroup

AnimationGroup containing creation of the lines and of the elements.

Examples
class CreateTableExample(Scene):
    def construct(self):
        table = Table(
            [["First", "Second"],
            ["Third","Fourth"]],
            row_labels=[Text("R1"), Text("R2")],
            col_labels=[Text("C1"), Text("C2")],
            include_outer_lines=True)
        self.play(table.create())
        self.wait()
get_cell(pos: Sequence[int] = (1, 1), **kwargs: Any) → Polygon

Returns one specific cell as a rectangular Polygon without the entry.

Parameters
pos

The position of a specific entry on the table. (1,1) being the top left entry of the table.

kwargs

Additional arguments to be passed to Polygon.

Returns
Polygon

Polygon mimicking one specific cell of the Table.

Examples
class GetCellExample(Scene):
    def construct(self):
        table = Table(
            [["First", "Second"],
            ["Third","Fourth"]],
            row_labels=[Text("R1"), Text("R2")],
            col_labels=[Text("C1"), Text("C2")])
        cell = table.get_cell((2,2), color=RED)
        self.add(table, cell)
get_col_labels() → VGroup

Return the column labels of the table.

Returns
VGroup

VGroup containing the column labels of the table.

Examples
class GetColLabelsExample(Scene):
    def construct(self):
        table = Table(
            [["First", "Second"],
            ["Third","Fourth"]],
            row_labels=[Text("R1"), Text("R2")],
            col_labels=[Text("C1"), Text("C2")])
        lab = table.get_col_labels()
        for item in lab:
            item.set_color(random_bright_color())
        self.add(table)
get_columns() → VGroup

Return columns of the table as a VGroup of VGroup.

Returns
VGroup

VGroup containing each column in a VGroup.

Examples
class GetColumnsExample(Scene):
    def construct(self):
        table = Table(
            [["First", "Second"],
            ["Third","Fourth"]],
            row_labels=[Text("R1"), Text("R2")],
            col_labels=[Text("C1"), Text("C2")])
        table.add(SurroundingRectangle(table.get_columns()[1]))
        self.add(table)
get_entries(pos: Sequence[int] | None = None) → VMobject | VGroup

Return the individual entries of the table (including labels) or one specific entry if the parameter, pos, is set.

Parameters
pos

The position of a specific entry on the table. (1,1) being the top left entry of the table.

Returns
Union[VMobject, VGroup]

VGroup containing all entries of the table (including labels) or the VMobject at the given position if pos is set.

Examples
class GetEntriesExample(Scene):
    def construct(self):
        table = Table(
            [["First", "Second"],
            ["Third","Fourth"]],
            row_labels=[Text("R1"), Text("R2")],
            col_labels=[Text("C1"), Text("C2")])
        ent = table.get_entries()
        for item in ent:
            item.set_color(random_bright_color())
        table.get_entries((2,2)).rotate(PI)
        self.add(table)
get_entries_without_labels(pos: Sequence[int] | None = None) → VMobject | VGroup

Return the individual entries of the table (without labels) or one specific entry if the parameter, pos, is set.

Parameters
pos

The position of a specific entry on the table. (1,1) being the top left entry of the table (without labels).

Returns
Union[VMobject, VGroup]

VGroup containing all entries of the table (without labels) or the VMobject at the given position if pos is set.

Examples
class GetEntriesWithoutLabelsExample(Scene):
    def construct(self):
        table = Table(
            [["First", "Second"],
            ["Third","Fourth"]],
            row_labels=[Text("R1"), Text("R2")],
            col_labels=[Text("C1"), Text("C2")])
        ent = table.get_entries_without_labels()
        colors = [BLUE, GREEN, YELLOW, RED]
        for k in range(len(colors)):
            ent[k].set_color(colors[k])
        table.get_entries_without_labels((2,2)).rotate(PI)
        self.add(table)
get_highlighted_cell(pos: Sequence[int] = (1, 1), color: ManimColor | int | str | NDArray[int64] | tuple[int, int, int] | NDArray[float64] | tuple[float, float, float] | tuple[int, int, int, int] | tuple[float, float, float, float] = ManimColor('#FFFF00'), **kwargs: Any) → BackgroundRectangle

Returns a BackgroundRectangle of the cell at the given position.

Parameters
pos

The position of a specific entry on the table. (1,1) being the top left entry of the table.

color

The color used to highlight the cell.

kwargs

Additional arguments to be passed to BackgroundRectangle.

Examples
class GetHighlightedCellExample(Scene):
    def construct(self):
        table = Table(
            [["First", "Second"],
            ["Third","Fourth"]],
            row_labels=[Text("R1"), Text("R2")],
            col_labels=[Text("C1"), Text("C2")])
        highlight = table.get_highlighted_cell((2,2), color=GREEN)
        table.add_to_back(highlight)
        self.add(table)
get_horizontal_lines() → VGroup

Return the horizontal lines of the table.

Returns
VGroup

VGroup containing all the horizontal lines of the table.

Examples
class GetHorizontalLinesExample(Scene):
    def construct(self):
        table = Table(
            [["First", "Second"],
            ["Third","Fourth"]],
            row_labels=[Text("R1"), Text("R2")],
            col_labels=[Text("C1"), Text("C2")])
        table.get_horizontal_lines().set_color(RED)
        self.add(table)
get_labels() → VGroup

Returns the labels of the table.

Returns
VGroup

VGroup containing all the labels of the table.

Examples
class GetLabelsExample(Scene):
    def construct(self):
        table = Table(
            [["First", "Second"],
            ["Third","Fourth"]],
            row_labels=[Text("R1"), Text("R2")],
            col_labels=[Text("C1"), Text("C2")])
        lab = table.get_labels()
        colors = [BLUE, GREEN, YELLOW, RED]
        for k in range(len(colors)):
            lab[k].set_color(colors[k])
        self.add(table)
get_row_labels() → VGroup

Return the row labels of the table.

Returns
VGroup

VGroup containing the row labels of the table.

Examples
class GetRowLabelsExample(Scene):
    def construct(self):
        table = Table(
            [["First", "Second"],
            ["Third","Fourth"]],
            row_labels=[Text("R1"), Text("R2")],
            col_labels=[Text("C1"), Text("C2")])
        lab = table.get_row_labels()
        for item in lab:
            item.set_color(random_bright_color())
        self.add(table)
get_rows() → VGroup

Return the rows of the table as a VGroup of VGroup.

Returns
VGroup

VGroup containing each row in a VGroup.

Examples
class GetRowsExample(Scene):
    def construct(self):
        table = Table(
            [["First", "Second"],
            ["Third","Fourth"]],
            row_labels=[Text("R1"), Text("R2")],
            col_labels=[Text("C1"), Text("C2")])
        table.add(SurroundingRectangle(table.get_rows()[1]))
        self.add(table)
get_vertical_lines() → VGroup

Return the vertical lines of the table.

Returns
VGroup

VGroup containing all the vertical lines of the table.

Examples
class GetVerticalLinesExample(Scene):
    def construct(self):
        table = Table(
            [["First", "Second"],
            ["Third","Fourth"]],
            row_labels=[Text("R1"), Text("R2")],
            col_labels=[Text("C1"), Text("C2")])
        table.get_vertical_lines()[0].set_color(RED)
        self.add(table)
scale(scale_factor: float, scale_stroke: bool = False, **kwargs: Any) → Self

Scale the size by a factor.

Default behavior is to scale about the center of the vmobject.

Parameters
scale_factor

The scaling factor \(\alpha\). If \(0 < |\alpha| < 1\), the mobject will shrink, and for \(|\alpha| > 1\) it will grow. Furthermore, if \(\alpha < 0\), the mobject is also flipped.

scale_stroke

Boolean determining if each submobject's outline is scaled when the object is scaled. If enabled, each submobject keeps its relative stroke width (for example, a submobject with a 2px outline scaled by a factor of .5 will have a 1px outline, while a submobject with 0px stroke remains at 0px).

kwargs

Additional keyword arguments passed to scale().

Returns
VMobject

self

Examples
class MobjectScaleExample(Scene):
    def construct(self):
        c1 = Circle(1, RED).set_x(-1)
        c2 = Circle(1, GREEN).set_x(1)

        vg = VGroup(c1, c2)
        vg.set_stroke(width=50)
        self.add(vg)

        self.play(
            c1.animate.scale(.25),
            c2.animate.scale(.25,
                scale_stroke=True)
        )
See also

move_to()

set_column_colors(*colors: Iterable[ManimColor | int | str | NDArray[int64] | tuple[int, int, int] | NDArray[float64] | tuple[float, float, float] | tuple[int, int, int, int] | tuple[float, float, float, float]]) → Self

Set individual colors for each column of the table.

Parameters
colors

An iterable of colors; each color corresponds to a column.

Examples
class SetColumnColorsExample(Scene):
    def construct(self):
        table = Table(
            [["First", "Second"],
            ["Third","Fourth"]],
            row_labels=[Text("R1"), Text("R2")],
            col_labels=[Text("C1"), Text("C2")]
        ).set_column_colors([RED,BLUE], GREEN)
        self.add(table)
set_row_colors(*colors: Iterable[ManimColor | int | str | NDArray[int64] | tuple[int, int, int] | NDArray[float64] | tuple[float, float, float] | tuple[int, int, int, int] | tuple[float, float, float, float]]) → Self

Set individual colors for each row of the table.

Parameters
colors

An iterable of colors; each color corresponds to a row.

Examples
class SetRowColorsExample(Scene):
    def construct(self):
        table = Table(
            [["First", "Second"],
            ["Third","Fourth"]],
            row_labels=[Text("R1"), Text("R2")],
            col_labels=[Text("C1"), Text("C2")]
        ).set_row_colors([RED,BLUE], GREEN)
        self.add(table)

ValueTracker

不可见数值容器:本身不渲染,配合 get_value/set_value 与 add_updater 驱动一切「数值驱动的动画」。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Mobject" -> "ValueTracker"; }

参数

快速上手

vt = ValueTracker(0)
number.add_updater(lambda d: d.set_value(vt.get_value()))
self.play(vt.animate.set_value(10))

API 文档

class manim.ValueTracker(value: float = 0, **kwargs: Any)

基类:Mobject

A mobject that can be used for tracking (real-valued) parameters. Useful for animating parameter changes.

Not meant to be displayed. Instead the position encodes some number, often one which another animation or continual_animation uses for its update function, and by treating it as a mobject it can still be animated and manipulated just like anything else.

This value changes continuously when animated using the animate syntax.

Examples

class ValueTrackerExample(Scene):
    def construct(self):
        number_line = NumberLine()
        pointer = Vector(DOWN)
        label = MathTex("x").add_updater(lambda m: m.next_to(pointer, UP))

        tracker = ValueTracker(0)
        pointer.add_updater(
            lambda m: m.next_to(
                        number_line.n2p(tracker.get_value()),
                        UP
                    )
        )
        self.add(number_line, pointer,label)
        tracker += 1.5
        self.wait(1)
        tracker -= 4
        self.wait(0.5)
        self.play(tracker.animate.set_value(5))
        self.wait(0.5)
        self.play(tracker.animate.set_value(3))
        self.play(tracker.animate.increment_value(-2))
        self.wait(0.5)

备注

You can also link ValueTrackers to updaters. In this case, you have to make sure that the ValueTracker is added to the scene by add

class ValueTrackerExample(Scene):
    def construct(self):
        tracker = ValueTracker(0)
        label = Dot(radius=3).add_updater(lambda x : x.set_x(tracker.get_value()))
        self.add(label)
        self.add(tracker)
        tracker.add_updater(lambda mobject, dt: mobject.increment_value(dt))
        self.wait(2)
get_value() → float

Get the current value of this ValueTracker.

increment_value(d_value: float) → Self

Increments (adds) a scalar value to the ValueTracker.

interpolate(mobject1: Mobject, mobject2: Mobject, alpha: float, path_func: PathFuncType = <function interpolate>) → Self

Turns self into an interpolation between mobject1 and mobject2.

set_value(value: float) → Self

Sets a new scalar value to the ValueTracker.

VectorField

向量场基类:ArrowVectorField 与 StreamLines 的共同父类,负责采样与归一化逻辑。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Mobject" -> "VMobject"; "VMobject" -> "VGroup"; "VGroup" -> "VectorField"; }

参数

func

—

color

None

color_scheme

None

min_color_scheme_value

0,float

max_color_scheme_value

2,float

colors

[ManimColor('#236B8E'), Man…

API 文档

class manim.VectorField(func: Callable[[Point3D], Vector3D], color: ParsableManimColor | None = None, color_scheme: Callable[[Vector3D], float] | None = None, min_color_scheme_value: float = 0, max_color_scheme_value: float = 2, colors: Sequence[ParsableManimColor] = [ManimColor('#236B8E'), ManimColor('#83C167'), ManimColor('#F7D96F'), ManimColor('#FC6255')], **kwargs)

基类:VGroup

A vector field.

Vector fields are based on a function defining a vector at every position. This class does by default not include any visible elements but provides methods to move other Mobject s along the vector field.

Parameters

func

The function defining the rate of change at every position of the VectorField.

color

The color of the vector field. If set, position-specific coloring is disabled.

color_scheme

A function mapping a vector to a single value. This value gives the position in the color gradient defined using min_color_scheme_value, max_color_scheme_value and colors.

min_color_scheme_value

The value of the color_scheme function to be mapped to the first color in colors. Lower values also result in the first color of the gradient.

max_color_scheme_value

The value of the color_scheme function to be mapped to the last color in colors. Higher values also result in the last color of the gradient.

colors

The colors defining the color gradient of the vector field.

kwargs

Additional arguments to be passed to the VGroup constructor

fit_to_coordinate_system(coordinate_system: CoordinateSystem) → Self

Scale the vector field to fit a coordinate system.

This method is useful when the vector field is defined in a coordinate system different from the one used to display the vector field.

This method can only be used once because it transforms the origin of each vector.

Parameters
coordinate_system

The coordinate system to fit the vector field to.

get_colored_background_image(sampling_rate: int = 5) → Image

Generate an image that displays the vector field.

The color at each position is calculated by passing the positing through a series of steps: Calculate the vector field function at that position, map that vector to a single value using self.color_scheme and finally generate a color from that value using the color gradient.

Parameters
sampling_rate

The stepsize at which pixels get included in the image. Lower values give more accurate results, but may take a long time to compute.

Returns
Image.Imgae

The vector field image.

get_nudge_updater(speed: float = 1, pointwise: bool = False) → Callable[[Mobject, float], Mobject]

Get an update function to move a Mobject along the vector field.

When used with add_updater(), the mobject will move along the vector field, where its speed is determined by the magnitude of the vector field.

Parameters
speed

At speed=1 the distance a mobject moves per second is equal to the magnitude of the vector field along its path. The speed value scales the speed of such a mobject.

pointwise

Whether to move the mobject along the vector field. See nudge() for details.

Returns
Callable[[Mobject, float], Mobject]

The update function.

get_vectorized_rgba_gradient_function(start: float, end: float, colors: Iterable[ParsableManimColor]) → Callable[[Sequence[float], float], FloatRGBA_Array]

Generates a gradient of rgbas as a numpy array

Parameters
start

start value used for inverse interpolation at inverse_interpolate()

end

end value used for inverse interpolation at inverse_interpolate()

colors

list of colors to generate the gradient

Returns

function to generate the gradients as numpy arrays representing rgba values

nudge(mob: Mobject, dt: float = 1, substeps: int = 1, pointwise: bool = False) → Self

Nudge a Mobject along the vector field.

Parameters
mob

The mobject to move along the vector field

dt

A scalar to the amount the mobject is moved along the vector field. The actual distance is based on the magnitude of the vector field.

substeps

The amount of steps the whole nudge is divided into. Higher values give more accurate approximations.

pointwise

Whether to move the mobject along the vector field. If False the vector field takes effect on the center of the given Mobject. If True the vector field takes effect on the points of the individual points of the Mobject, potentially distorting it.

Returns
VectorField

This vector field.

Examples
class Nudging(Scene):
    def construct(self):
        func = lambda pos: np.sin(pos[1] / 2) * RIGHT + np.cos(pos[0] / 2) * UP
        vector_field = ArrowVectorField(
            func, x_range=[-7, 7, 1], y_range=[-4, 4, 1], length_func=lambda x: x / 2
        )
        self.add(vector_field)
        circle = Circle(radius=2).shift(LEFT)
        self.add(circle.copy().set_color(GRAY))
        dot = Dot().move_to(circle)

        vector_field.nudge(circle, -2, 60, True)
        vector_field.nudge(dot, -2, 60)

        circle.add_updater(vector_field.get_nudge_updater(pointwise=True))
        dot.add_updater(vector_field.get_nudge_updater())
        self.add(circle, dot)
        self.wait(6)
nudge_submobjects(dt: float = 1, substeps: int = 1, pointwise: bool = False) → Self

Apply a nudge along the vector field to all submobjects.

Parameters
dt

A scalar to the amount the mobject is moved along the vector field. The actual distance is based on the magnitude of the vector field.

substeps

The amount of steps the whole nudge is divided into. Higher values give more accurate approximations.

pointwise

Whether to move the mobject along the vector field. See nudge() for details.

Returns
VectorField

This vector field.

static scale_func(func: Callable[[ndarray], ndarray], scalar: float) → Callable[[ndarray], ndarray]

Scale a vector field function.

Parameters
func

The function defining a vector field.

scalar

The scalar to be applied to the vector field.

Examples
class ScaleVectorFieldFunction(Scene):
    def construct(self):
        func = lambda pos: np.sin(pos[1]) * RIGHT + np.cos(pos[0]) * UP
        vector_field = ArrowVectorField(func)
        self.add(vector_field)
        self.wait()

        func = VectorField.scale_func(func, 0.5)
        self.play(vector_field.animate.become(ArrowVectorField(func)))
        self.wait()
Returns
Callable[[np.ndarray], np.ndarray]

The scaled vector field function.

static shift_func(func: Callable[[ndarray], ndarray], shift_vector: ndarray) → Callable[[ndarray], ndarray]

Shift a vector field function.

Parameters
func

The function defining a vector field.

shift_vector

The shift to be applied to the vector field.

Returns
Callable[[np.ndarray], np.ndarray]

The shifted vector field function.

start_submobject_movement(speed: float = 1, pointwise: bool = False) → Self

Start continuously moving all submobjects along the vector field.

Calling this method multiple times will result in removing the previous updater created by this method.

Parameters
speed

The speed at which to move the submobjects. See get_nudge_updater() for details.

pointwise

Whether to move the mobject along the vector field. See nudge() for details.

Returns
VectorField

This vector field.

stop_submobject_movement() → Self

Stops the continuous movement started using start_submobject_movement().

Returns
VectorField

This vector field.