API 参考:图表与坐标(graphing)

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

Axes

平面直角坐标系:x/y 轴 + 刻度 + 可扩展的坐标转换(c2p/p2c),函数绘图的主舞台。

继承关系

G CoordinateSystem CoordinateSystem Mobject Mobject CoordinateSystem->Mobject VMobject VMobject Mobject->VMobject VGroup VGroup VMobject->VGroup Axes Axes VGroup->Axes

参数

x_range

None,Sequence[float] | None

y_range

None,Sequence[float] | None

x_length

12,float | None

y_length

6,float | None

axis_config

None,dict | None

x_axis_config

None,dict | None

y_axis_config

None,dict | None

tips

True,bool

快速上手

axes = Axes(x_range=[-3, 3], y_range=[-2, 2])
self.add(axes)
self.play(Create(axes.plot(lambda x: x**2)))

API 文档

class manim.Axes(x_range: Sequence[float] | None = None, y_range: Sequence[float] | None = None, x_length: float | None = 12, y_length: float | None = 6, axis_config: dict | None = None, x_axis_config: dict | None = None, y_axis_config: dict | None = None, tips: bool = True, **kwargs: Any)

基类:VGroup, CoordinateSystem

coords_to_point(*coords: float | Sequence[float] | Sequence[Sequence[float]] | ndarray) → ndarray

Accepts coordinates from the axes and returns a point with respect to the scene. Equivalent to ax @ (coord1)

Parameters

coords

The coordinates. Each coord is passed as a separate argument: ax.coords_to_point(1, 2, 3).

Also accepts a list of coordinates

ax.coords_to_point( [x_0, x_1, ...], [y_0, y_1, ...], ... )

ax.coords_to_point( [[x_0, y_0, z_0], [x_1, y_1, z_1]] )

A single coordinate can also be passed as a flat list or 1D array:

ax.coords_to_point( [x, y, z] )

Returns

np.ndarray

A point with respect to the scene's coordinate system. The shape of the array will be similar to the shape of the input.

Examples

>>> from manim import Axes
>>> import numpy as np
>>> ax = Axes()
>>> np.around(ax.coords_to_point(1, 0, 0), 2)
array([0.86, 0.  , 0.  ])
>>> np.around(ax @ (1, 0, 0), 2)
array([0.86, 0.  , 0.  ])
>>> np.around(ax.coords_to_point([[0, 1], [1, 1], [1, 0]]), 2)
array([[0.  , 0.75, 0.  ],
       [0.86, 0.75, 0.  ],
       [0.86, 0.  , 0.  ]])
>>> np.around(
...     ax.coords_to_point([0, 1, 1], [1, 1, 0]), 2
... )  # Transposed version of the above
array([[0.  , 0.86, 0.86],
       [0.75, 0.75, 0.  ],
       [0.  , 0.  , 0.  ]])
>>> np.around(ax.coords_to_point([1, 0, 0]), 2)
array([0.86, 0.  , 0.  ])
>>> np.around(ax.coords_to_point(np.array([1, 0])), 2)
array([0.86, 0.  , 0.  ])
class CoordsToPointExample(Scene):
    def construct(self):
        ax = Axes().add_coordinates()

        # a dot with respect to the axes
        dot_axes = Dot(ax.coords_to_point(2, 2), color=GREEN)
        lines = ax.get_lines_to_point(ax.c2p(2,2))

        # a dot with respect to the scene
        # the default plane corresponds to the coordinates of the scene.
        plane = NumberPlane()
        dot_scene = Dot((2,2,0), color=RED)

        self.add(plane, dot_scene, ax, dot_axes, lines)
get_axes() → VGroup

Gets the axes.

Returns

VGroup

A pair of axes.

get_axis_labels(x_label: float | str | Mobject = 'x', y_label: float | str | Mobject = 'y') → VGroup

Defines labels for the x-axis and y-axis of the graph.

For increased control over the position of the labels, use get_x_axis_label() and get_y_axis_label().

Parameters

x_label

The label for the x_axis. Defaults to MathTex for str and float inputs.

y_label

The label for the y_axis. Defaults to MathTex for str and float inputs.

Returns

VGroup

A VGroup of the labels for the x_axis and y_axis.

Examples

class GetAxisLabelsExample(Scene):
    def construct(self):
        ax = Axes()
        labels = ax.get_axis_labels(
            Tex("x-axis").scale(0.7), Text("y-axis").scale(0.45)
        )
        self.add(ax, labels)
plot_line_graph(x_values: Iterable[float], y_values: Iterable[float], z_values: Iterable[float] | None = None, line_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'), add_vertex_dots: bool = True, vertex_dot_radius: float = 0.08, vertex_dot_style: dict[str, Any] | None = None, **kwargs: Any) → VDict

Draws a line graph.

The graph connects the vertices formed from zipping x_values, y_values and z_values. Also adds Dots at the vertices if add_vertex_dots is set to True.

Parameters

x_values

Iterable of values along the x-axis.

y_values

Iterable of values along the y-axis.

z_values

Iterable of values (zeros if z_values is None) along the z-axis.

line_color

Color for the line graph.

add_vertex_dots

Whether or not to add Dot at each vertex.

vertex_dot_radius

Radius for the Dot at each vertex.

vertex_dot_style

Style arguments to be passed into Dot at each vertex.

kwargs

Additional arguments to be passed into VMobject.

Returns

VDict

A VDict containing both the line and dots (if specified). The line can be accessed with: line_graph["line_graph"]. The dots can be accessed with: line_graph["vertex_dots"].

Examples

class LineGraphExample(Scene):
    def construct(self):
        plane = NumberPlane(
            x_range = (0, 7),
            y_range = (0, 5),
            x_length = 7,
            axis_config={"include_numbers": True},
        )
        plane.center()
        line_graph = plane.plot_line_graph(
            x_values = [0, 1.5, 2, 2.8, 4, 6.25],
            y_values = [1, 3, 2.25, 4, 2.5, 1.75],
            line_color=GOLD_E,
            vertex_dot_style=dict(stroke_width=3,  fill_color=PURPLE),
            stroke_width = 4,
        )
        self.add(plane, line_graph)
point_to_coords(point: Sequence[float]) → ndarray

Accepts a point from the scene and returns its coordinates with respect to the axes.

Parameters

point

The point, i.e. RIGHT or [0, 1, 0]. Also accepts a list of points as [RIGHT, [0, 1, 0]].

Returns

np.ndarray[float]

The coordinates on the axes, i.e. [4.0, 7.0]. Or a list of coordinates if point is a list of points.

Examples

>>> from manim import Axes, RIGHT
>>> import numpy as np
>>> ax = Axes(x_range=[0, 10, 2])
>>> np.around(ax.point_to_coords(RIGHT), 2)
array([5.83, 0.  ])
>>> np.around(ax.point_to_coords([[0, 0, 1], [1, 0, 0]]), 2)
array([[5.  , 0.  ],
       [5.83, 0.  ]])
class PointToCoordsExample(Scene):
    def construct(self):
        ax = Axes(x_range=[0, 10, 2]).add_coordinates()
        circ = Circle(radius=0.5).shift(UR * 2)

        # get the coordinates of the circle with respect to the axes
        coords = np.around(ax.point_to_coords(circ.get_right()), decimals=2)

        label = (
            Matrix([[coords[0]], [coords[1]]]).scale(0.75).next_to(circ, RIGHT)
        )

        self.add(ax, circ, label, Dot(circ.get_right()))

BarChart

柱状图:数值列表一键成图,柱色、标签、方向全能调,数据可视化入门件。

继承关系

G CoordinateSystem CoordinateSystem Mobject Mobject CoordinateSystem->Mobject VMobject VMobject Mobject->VMobject VGroup VGroup VMobject->VGroup Axes Axes VGroup->Axes BarChart BarChart Axes->BarChart

参数

values

—,MutableSequence[float]

bar_names

None,Sequence[str] | None

y_range

None,Sequence[float] | None

x_length

None,float | None

y_length

None,float | None

bar_colors

['#003f5c', '#58508d', '#bc…,Iterable[str]

bar_width

0.6,float

bar_fill_opacity

0.7,float

bar_stroke_width

3,float

快速上手

chart = BarChart(values=[3, 1, 4, 1, 5])

API 文档

class manim.BarChart(values: MutableSequence[float], bar_names: Sequence[str] | None = None, y_range: Sequence[float] | None = None, x_length: float | None = None, y_length: float | None = None, bar_colors: Iterable[str] = ['#003f5c', '#58508d', '#bc5090', '#ff6361', '#ffa600'], bar_width: float = 0.6, bar_fill_opacity: float = 0.7, bar_stroke_width: float = 3, **kwargs: Any)

基类:Axes

change_bar_values(values: Iterable[float], update_colors: bool = True) → Self

Updates the height of the bars of the chart.

Parameters

values

The values that will be used to update the height of the bars. Does not have to match the number of bars.

update_colors

Whether to re-initalize the colors of the bars based on self.bar_colors.

Examples

class ChangeBarValuesExample(Scene):
    def construct(self):
        values=[-10, -8, -6, -4, -2, 0, 2, 4, 6, 8, 10]

        chart = BarChart(
            values,
            y_range=[-10, 10, 2],
            y_axis_config={"font_size": 24},
        )
        self.add(chart)

        chart.change_bar_values(list(reversed(values)))
        self.add(chart.get_bar_labels(font_size=24))
get_bar_labels(color: 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, font_size: float = 24, buff: float = 0.25, label_constructor: type[MathTex] = <class 'manim.mobject.text.tex_mobject.Tex'>) → VGroup

Annotates each bar with its corresponding value. Use self.bar_labels to access the labels after creation.

Parameters

color

The color of each label. By default None and is based on the parent's bar color.

font_size

The font size of each label.

buff

The distance from each label to its bar. By default 0.4.

label_constructor

The Mobject class to construct the labels, by default Tex.

Examples

class GetBarLabelsExample(Scene):
    def construct(self):
        chart = BarChart(values=[10, 9, 8, 7, 6, 5, 4, 3, 2, 1], y_range=[0, 10, 1])

        c_bar_lbls = chart.get_bar_labels(
            color=WHITE, label_constructor=MathTex, font_size=36
        )

        self.add(chart, c_bar_lbls)

ComplexPlane

复平面:实轴 + 虚轴 + 复数标注,复变函数可视化的坐标底图。

继承关系

G CoordinateSystem CoordinateSystem Mobject Mobject CoordinateSystem->Mobject VMobject VMobject Mobject->VMobject VGroup VGroup VMobject->VGroup Axes Axes VGroup->Axes NumberPlane NumberPlane Axes->NumberPlane ComplexPlane ComplexPlane NumberPlane->ComplexPlane

快速上手

plane = ComplexPlane()

API 文档

class manim.ComplexPlane(**kwargs: Any)

基类:NumberPlane

add_coordinates(*numbers: Iterable[float | complex], **kwargs: Any) → Self

Adds the labels produced from get_coordinate_labels() to the plane.

Parameters

numbers

An iterable of floats/complex numbers. Floats are positioned along the x-axis, complex numbers along the y-axis.

kwargs

Additional arguments to be passed to get_number_mobject(), i.e. DecimalNumber.

get_coordinate_labels(*numbers: Iterable[float | complex], **kwargs: Any) → VGroup

Generates the DecimalNumber mobjects for the coordinates of the plane.

Parameters

numbers

An iterable of floats/complex numbers. Floats are positioned along the x-axis, complex numbers along the y-axis.

kwargs

Additional arguments to be passed to get_number_mobject(), i.e. DecimalNumber.

Returns

VGroup

A VGroup containing the positioned label mobjects.

n2p(number: float | complex) → ndarray

Abbreviation for number_to_point().

number_to_point(number: float | complex) → ndarray

Accepts a float/complex number and returns the equivalent point on the plane.

Parameters

number

The number. Can be a float or a complex number.

Returns

np.ndarray

The point on the plane.

p2n(point: Point3DLike) → complex

Abbreviation for point_to_number().

point_to_number(point: Point3DLike) → complex

Accepts a point and returns a complex number equivalent to that point on the plane.

Parameters

point

The point in manim's coordinate-system

Returns

complex

A complex number consisting of real and imaginary components.

CoordinateSystem

一切坐标系(Axes、NumberLine、PolarPlane 等)的基类:统一提供 c2p/p2c 坐标变换与 get_graph 等接口。

参数

x_range

None,Sequence[float] | None

y_range

None,Sequence[float] | None

x_length

None,float | None

y_length

None,float | None

dimension

2,int

API 文档

class manim.CoordinateSystem(x_range: Sequence[float] | None = None, y_range: Sequence[float] | None = None, x_length: float | None = None, y_length: float | None = None, dimension: int = 2)

基类:object

add_coordinates(*axes_numbers: Iterable[float] | None | dict[float, str | float | Mobject], **kwargs: Any) → Self

Adds labels to the axes. Use Axes.coordinate_labels to access the coordinates after creation.

Parameters

axes_numbers

The numbers to be added to the axes. Use None to represent an axis with default labels.

Examples

ax = ThreeDAxes()
x_labels = range(-4, 5)
z_labels = range(-4, 4, 2)
ax.add_coordinates(
    x_labels, None, z_labels
)  # default y labels, custom x & z labels
ax.add_coordinates(x_labels)  # only x labels

You can also specifically control the position and value of the labels using a dict.

ax = Axes(x_range=[0, 7])
x_pos = [x for x in range(1, 8)]

# strings are automatically converted into a Tex mobject.
x_vals = [
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday",
    "Sunday",
]
x_dict = dict(zip(x_pos, x_vals))
ax.add_coordinates(x_dict)
angle_of_tangent(x: float, graph: ParametricFunction, dx: float = 1e-08) → float

Returns the angle to the x-axis of the tangent to the plotted curve at a particular x-value.

Parameters

x

The x-value at which the tangent must touch the curve.

graph

The ParametricFunction for which to calculate the tangent.

dx

The change in x used to determine the angle of the tangent to the curve.

Returns

float

The angle of the tangent to the curve.

Examples

ax = Axes()
curve = ax.plot(lambda x: x**2)
ax.angle_of_tangent(x=3, graph=curve)
# 1.4056476493802699
c2p(*coords: float | Sequence[float] | Sequence[Sequence[float]] | ndarray) → ndarray

Abbreviation for coords_to_point()

get_T_label(x_val: float, graph: ParametricFunction, label: float | str | Mobject | None = None, label_color: 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, triangle_size: float = 0.25, triangle_color: 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=ManimColor('#FFFFFF'), line_func: type[Line] = <class 'manim.mobject.geometry.line.Line'>, line_color: 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('#FFFF00')) → VGroup

Creates a labelled triangle marker with a vertical line from the x-axis to a curve at a given x-value.

Parameters

x_val

The position along the curve at which the label, line and triangle will be constructed.

graph

The ParametricFunction for which to construct the label.

label

The label of the vertical line and triangle.

label_color

The color of the label.

triangle_size

The size of the triangle.

triangle_color

The color of the triangle.

line_func

The function used to construct the vertical line.

line_color

The color of the vertical line.

Returns

VGroup

A VGroup of the label, triangle and vertical line mobjects.

Examples

class TLabelExample(Scene):
    def construct(self):
        # defines the axes and linear function
        axes = Axes(x_range=[-1, 10], y_range=[-1, 10], x_length=9, y_length=6)
        func = axes.plot(lambda x: x, color=BLUE)
        # creates the T_label
        t_label = axes.get_T_label(x_val=4, graph=func, label=Tex("x-value"))
        self.add(axes, func, t_label)
get_area(graph: ParametricFunction, x_range: tuple[float, float] | None = None, 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] | 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]] = (ManimColor('#58C4DD'), ManimColor('#83C167')), opacity: float = 0.3, bounded_graph: ParametricFunction | None = None, **kwargs: Any) → Polygon

Returns a Polygon representing the area under the graph passed.

Parameters

graph

The graph/curve for which the area needs to be gotten.

x_range

The range of the minimum and maximum x-values of the area. x_range = [x_min, x_max].

color

The color of the area. Creates a gradient if a list of colors is provided.

opacity

The opacity of the area.

bounded_graph

If a secondary graph is specified, encloses the area between the two curves.

kwargs

Additional parameters passed to Polygon.

Returns

Polygon

The Polygon representing the area.

Raises

ValueError

When x_ranges do not match (either area x_range, graph's x_range or bounded_graph's x_range).

Examples

class GetAreaExample(Scene):
    def construct(self):
        ax = Axes().add_coordinates()
        curve = ax.plot(lambda x: 2 * np.sin(x), color=DARK_BLUE)
        area = ax.get_area(
            curve,
            x_range=(PI / 2, 3 * PI / 2),
            color=(GREEN_B, GREEN_D),
            opacity=1,
        )

        self.add(ax, curve, area)
get_graph_label(graph: ParametricFunction, label: float | str | VMobject = 'f(x)', x_val: float | None = None, direction: Sequence[float] = array([1., 0., 0.]), buff: float = 0.25, 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, dot: bool = False, dot_config: dict[str, Any] | None = None) → Mobject

Creates a properly positioned label for the passed graph, with an optional dot.

Parameters

graph

The curve.

label

The label for the function's curve. Defaults to MathTex for str and float inputs.

x_val

The x_value along the curve that positions the label.

direction

The cartesian position, relative to the curve that the label will be at --> LEFT, RIGHT.

buff

The distance between the curve and the label.

color

The color of the label. Defaults to the color of the curve.

dot

Whether to add a dot at the point on the graph.

dot_config

Additional parameters to be passed to Dot.

Returns

Mobject

The positioned label and Dot, if applicable.

Examples

class GetGraphLabelExample(Scene):
    def construct(self):
        ax = Axes()
        sin = ax.plot(lambda x: np.sin(x), color=PURPLE_B)
        label = ax.get_graph_label(
            graph=sin,
            label= MathTex(r"\frac{\pi}{2}"),
            x_val=PI / 2,
            dot=True,
            direction=UR,
        )

        self.add(ax, sin, label)
get_horizontal_line(point: Point3DLike, **kwargs: Any) → Line

A horizontal line from the y-axis to a given point in the scene.

Parameters

point

The point to which the horizontal line will be drawn.

kwargs

Additional parameters to be passed to get_line_from_axis_to_point.

Returns

Line

A horizontal line from the y-axis to the point.

Examples

class GetHorizontalLineExample(Scene):
    def construct(self):
        ax = Axes().add_coordinates()
        point = ax @ (-4, 1.5)

        dot = Dot(point)
        line = ax.get_horizontal_line(point, line_func=Line)

        self.add(ax, line, dot)
get_line_from_axis_to_point(index: int, point: Point3DLike, line_config: dict | None = None, 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, stroke_width: float = 2) → DashedLine
get_line_from_axis_to_point(index: int, point: Point3DLike, line_func: type[LineType], line_config: dict | None = None, 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, stroke_width: float = 2) → LineType

Returns a straight line from a given axis to a point in the scene.

Parameters

index

Specifies the axis from which to draw the line. 0 = x_axis, 1 = y_axis

point

The point to which the line will be drawn.

line_func

The function of the Line mobject used to construct the line.

line_config

Optional arguments to passed to line_func.

color

The color of the line.

stroke_width

The stroke width of the line.

Returns

Line

The line from an axis to a point.

get_lines_to_point(point: Point3DLike, **kwargs: Any) → VGroup

Generate both horizontal and vertical lines from the axis to a point.

Parameters

point

A point on the scene.

kwargs

Additional parameters to be passed to get_line_from_axis_to_point()

Returns

VGroup

A VGroup of the horizontal and vertical lines.

Examples

class GetLinesToPointExample(Scene):
    def construct(self):
        ax = Axes()
        circ = Circle(radius=0.5).move_to([-4, -1.5, 0])

        lines_1 = ax.get_lines_to_point(circ.get_right(), color=GREEN_B)
        lines_2 = ax.get_lines_to_point(circ.get_corner(DL), color=BLUE_B)
        self.add(ax, lines_1, lines_2, circ)
get_origin() → Point3D

Gets the origin of Axes.

Returns

np.ndarray

The center point.

get_riemann_rectangles(graph: ParametricFunction, x_range: Sequence[float] | None = None, dx: float = 0.1, input_sample_type: str = 'left', stroke_width: float = 1, stroke_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'), fill_opacity: float = 1, color: 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]] | 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('#58C4DD'), ManimColor('#83C167')), show_signed_area: bool = True, bounded_graph: ParametricFunction | None = None, blend: bool = False, width_scale_factor: float = 1.001) → VGroup

Generates a VGroup of the Riemann Rectangles for a given curve.

Parameters

graph

The graph whose area will be approximated by Riemann rectangles.

x_range

The minimum and maximum x-values of the rectangles. x_range = [x_min, x_max].

dx

The change in x-value that separates each rectangle.

input_sample_type

Can be any of "left", "right" or "center". Refers to where the sample point for the height of each Riemann Rectangle will be inside the segments of the partition.

stroke_width

The stroke_width of the border of the rectangles.

stroke_color

The color of the border of the rectangle.

fill_opacity

The opacity of the rectangles.

color

The colors of the rectangles. Creates a balanced gradient if multiple colors are passed.

show_signed_area

Indicates negative area when the curve dips below the x-axis by inverting its color.

blend

Sets the stroke_color to fill_color, blending the rectangles without clear separation.

bounded_graph

If a secondary graph is specified, encloses the area between the two curves.

width_scale_factor

The factor by which the width of the rectangles is scaled.

Returns

VGroup

A VGroup containing the Riemann Rectangles.

Examples

class GetRiemannRectanglesExample(Scene):
    def construct(self):
        ax = Axes(y_range=[-2, 10])
        quadratic = ax.plot(lambda x: 0.5 * x ** 2 - 0.5)

        # the rectangles are constructed from their top right corner.
        # passing an iterable to `color` produces a gradient
        rects_right = ax.get_riemann_rectangles(
            quadratic,
            x_range=[-4, -3],
            dx=0.25,
            color=(TEAL, BLUE_B, DARK_BLUE),
            input_sample_type="right",
        )

        # the colour of rectangles below the x-axis is inverted
        # due to show_signed_area
        rects_left = ax.get_riemann_rectangles(
            quadratic, x_range=[-1.5, 1.5], dx=0.15, color=YELLOW
        )

        bounding_line = ax.plot(
            lambda x: 1.5 * x, color=BLUE_B, x_range=[3.3, 6]
        )
        bounded_rects = ax.get_riemann_rectangles(
            bounding_line,
            bounded_graph=quadratic,
            dx=0.15,
            x_range=[4, 5],
            show_signed_area=False,
            color=(MAROON_A, RED_B, PURPLE_D),
        )

        self.add(
            ax, bounding_line, quadratic, rects_right, rects_left, bounded_rects
        )
get_secant_slope_group(x: float, graph: ParametricFunction, dx: float | None = None, dx_line_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'), dy_line_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, dx_label: float | str | None = None, dy_label: float | str | None = None, include_secant_line: bool = True, secant_line_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('#83C167'), secant_line_length: float = 10) → VGroup
Creates two lines representing dx and df, the labels for dx and df, and

the secant to the curve at a particular x-value.

Parameters

x

The x-value at which the secant intersects the graph for the first time.

graph

The curve for which the secant will be found.

dx

The change in x after which the secant exits.

dx_line_color

The color of the line that indicates the change in x.

dy_line_color

The color of the line that indicates the change in y. Defaults to the color of graph.

dx_label

The label for the dx line. Defaults to MathTex for str and float inputs.

dy_label

The label for the dy line. Defaults to MathTex for str and float inputs.

include_secant_line

Whether to include the secant line in the graph, or just the df/dx lines and labels.

secant_line_color

The color of the secant line.

secant_line_length

The length of the secant line.

Returns

VGroup

A group containing the elements: dx_line, df_line, and if applicable also dx_label, df_label, secant_line.

Examples

class GetSecantSlopeGroupExample(Scene):
    def construct(self):
        ax = Axes(y_range=[-1, 7])
        graph = ax.plot(lambda x: 1 / 4 * x ** 2, color=BLUE)
        slopes = ax.get_secant_slope_group(
            x=2.0,
            graph=graph,
            dx=1.0,
            dx_label=Tex("dx = 1.0"),
            dy_label="dy",
            dx_line_color=GREEN_B,
            secant_line_length=4,
            secant_line_color=RED_D,
        )

        self.add(ax, graph, slopes)
get_vertical_line(point: Point3DLike, **kwargs: Any) → Line

A vertical line from the x-axis to a given point in the scene.

Parameters

point

The point to which the vertical line will be drawn.

kwargs

Additional parameters to be passed to get_line_from_axis_to_point.

Returns

Line

A vertical line from the x-axis to the point.

Examples

class GetVerticalLineExample(Scene):
    def construct(self):
        ax = Axes().add_coordinates()
        point = ax.coords_to_point(-3.5, 2)

        dot = Dot(point)
        line = ax.get_vertical_line(point, line_config={"dashed_ratio": 0.85})

        self.add(ax, line, dot)
get_vertical_lines_to_graph(graph: ParametricFunction, x_range: Sequence[float] | None = None, num_lines: int = 20, **kwargs: Any) → VGroup

Obtains multiple lines from the x-axis to the curve.

Parameters

graph

The graph along which the lines are placed.

x_range

A list containing the lower and and upper bounds of the lines: x_range = [x_min, x_max].

num_lines

The number of evenly spaced lines.

kwargs

Additional arguments to be passed to get_vertical_line().

Returns

VGroup

The VGroup of the evenly spaced lines.

Examples

class GetVerticalLinesToGraph(Scene):
    def construct(self):
        ax = Axes(
            x_range=[0, 8.0, 1],
            y_range=[-1, 1, 0.2],
            axis_config={"font_size": 24},
        ).add_coordinates()

        curve = ax.plot(lambda x: np.sin(x) / np.e ** 2 * x)

        lines = ax.get_vertical_lines_to_graph(
            curve, x_range=[0, 4], num_lines=30, color=BLUE
        )

        self.add(ax, curve, lines)
get_x_axis_label(label: float | str | VMobject, edge: Vector3D = array([1., 1., 0.]), direction: Vector3D = array([1., 1., 0.]), buff: float = 0.1, **kwargs: Any) → Mobject

Generate an x-axis label.

Parameters

label

The label. Defaults to MathTex for str and float inputs.

edge

The edge of the x-axis to which the label will be added, by default UR.

direction

Allows for further positioning of the label from an edge, by default UR.

buff

The distance of the label from the line.

Returns

Mobject

The positioned label.

Examples

class GetXAxisLabelExample(Scene):
    def construct(self):
        ax = Axes(x_range=(0, 8), y_range=(0, 5), x_length=8, y_length=5)
        x_label = ax.get_x_axis_label(
            Tex("$x$-values").scale(0.65), edge=DOWN, direction=DOWN, buff=0.5
        )
        self.add(ax, x_label)
get_y_axis_label(label: float | str | VMobject, edge: Vector3D = array([1., 1., 0.]), direction: Vector3D = array([1., 0.5, 0.]), buff: float = 0.1, **kwargs: Any) → Mobject

Generate a y-axis label.

Parameters

label

The label. Defaults to MathTex for str and float inputs.

edge

The edge of the y-axis to which the label will be added, by default UR.

direction

Allows for further positioning of the label from an edge, by default UR

buff

The distance of the label from the line.

Returns

Mobject

The positioned label.

Examples

class GetYAxisLabelExample(Scene):
    def construct(self):
        ax = Axes(x_range=(0, 8), y_range=(0, 5), x_length=8, y_length=5)
        y_label = ax.get_y_axis_label(
            Tex("$y$-values").scale(0.65).rotate(90 * DEGREES),
            edge=LEFT,
            direction=LEFT,
            buff=0.3,
        )
        self.add(ax, y_label)
i2gc(x: float, graph: ParametricFunction) → tuple[float, float]

Alias for input_to_graph_coords().

i2gp(x: float, graph: ParametricFunction) → ndarray

Alias for input_to_graph_point().

input_to_graph_coords(x: float, graph: ParametricFunction) → tuple[float, float]

Returns a tuple of the axis relative coordinates of the point on the graph based on the x-value given.

Examples

>>> from manim import Axes
>>> ax = Axes()
>>> parabola = ax.plot(lambda x: x**2)
>>> ax.input_to_graph_coords(x=3, graph=parabola)
(3, 9)
input_to_graph_point(x: float, graph: ParametricFunction | VMobject) → Point3D

Returns the coordinates of the point on a graph corresponding to an x value.

Parameters

x

The x-value of a point on the graph.

graph

The ParametricFunction on which the point lies.

Returns

np.ndarray

The coordinates of the point on the graph corresponding to the x value.

Raises

ValueError

When the target x is not in the range of the line graph.

Examples

class InputToGraphPointExample(Scene):
    def construct(self):
        ax = Axes()
        curve = ax.plot(lambda x : np.cos(x))

        # move a square to PI on the cosine curve.
        position = ax.input_to_graph_point(x=PI, graph=curve)
        sq = Square(side_length=1, color=YELLOW).move_to(position)

        self.add(ax, curve, sq)
p2c(point: Point3DLike) → list[ManimFloat]

Abbreviation for point_to_coords()

plot(function: Callable[[float], float], x_range: Sequence[float] | None = None, use_vectorized: bool = False, colorscale: 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]] | 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], float] | None = None, colorscale_axis: int = 1, **kwargs: Any) → ParametricFunction

Generates a curve based on a function.

Parameters

function

The function used to construct the ParametricFunction.

x_range

The range of the curve along the axes. x_range = [x_min, x_max, x_step].

use_vectorized

Whether to pass in the generated t value array to the function. Only use this if your function supports it. Output should be a numpy array of shape [y_0, y_1, ...]

colorscale

Colors of the function. Optional parameter used when coloring a function by values. Passing a list of colors and a colorscale_axis will color the function by y-value. Passing a list of tuples in the form (color, pivot) allows user-defined pivots where the color transitions.

colorscale_axis

Defines the axis on which the colorscale is applied (0 = x, 1 = y), default is y-axis (1).

kwargs

Additional parameters to be passed to ParametricFunction.

Returns

ParametricFunction

The plotted curve.

警告

This method may not produce accurate graphs since Manim currently relies on interpolation between evenly-spaced samples of the curve, instead of intelligent plotting. See the example below for some solutions to this problem.

Examples

class PlotExample(Scene):
    def construct(self):
        # construct the axes
        ax_1 = Axes(
            x_range=[0.001, 6],
            y_range=[-8, 2],
            x_length=5,
            y_length=3,
            tips=False,
        )
        ax_2 = ax_1.copy()
        ax_3 = ax_1.copy()

        # position the axes
        ax_1.to_corner(UL)
        ax_2.to_corner(UR)
        ax_3.to_edge(DOWN)
        axes = VGroup(ax_1, ax_2, ax_3)

        # create the logarithmic curves
        def log_func(x):
            return np.log(x)

        # a curve without adjustments; poor interpolation.
        curve_1 = ax_1.plot(log_func, color=PURE_RED)

        # disabling interpolation makes the graph look choppy as not enough
        # inputs are available
        curve_2 = ax_2.plot(log_func, use_smoothing=False, color=ORANGE)

        # taking more inputs of the curve by specifying a step for the
        # x_range yields expected results, but increases rendering time.
        curve_3 = ax_3.plot(
            log_func, x_range=(0.001, 6, 0.001), color=PURE_GREEN
        )

        curves = VGroup(curve_1, curve_2, curve_3)

        self.add(axes, curves)
plot_antiderivative_graph(graph: ParametricFunction, y_intercept: float = 0, samples: int = 50, use_vectorized: bool = False, **kwargs: Any) → ParametricFunction

Plots an antiderivative graph.

Parameters

graph

The graph for which the antiderivative will be found.

y_intercept

The y-value at which the graph intercepts the y-axis.

samples

The number of points to take the area under the graph.

use_vectorized

Whether to use the vectorized version of the antiderivative. This means to pass in the generated t value array to the function. Only use this if your function supports it. Output should be a numpy array of shape [y_0, y_1, ...]

kwargs

Any valid keyword argument of ParametricFunction.

Returns

ParametricFunction

The curve of the antiderivative.

备注

This graph is plotted from the values of area under the reference graph. The result might not be ideal if the reference graph contains uncalculatable areas from x=0.

Examples

class AntiderivativeExample(Scene):
    def construct(self):
        ax = Axes()
        graph1 = ax.plot(
            lambda x: (x ** 2 - 2) / 3,
            color=RED,
        )
        graph2 = ax.plot_antiderivative_graph(graph1, color=BLUE)
        self.add(ax, graph1, graph2)
plot_derivative_graph(graph: ParametricFunction, 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('#83C167'), **kwargs: Any) → ParametricFunction

Returns the curve of the derivative of the passed graph.

Parameters

graph

The graph for which the derivative will be found.

color

The color of the derivative curve.

kwargs

Any valid keyword argument of ParametricFunction.

Returns

ParametricFunction

The curve of the derivative.

Examples

class DerivativeGraphExample(Scene):
    def construct(self):
        ax = NumberPlane(y_range=[-1, 7], background_line_style={"stroke_opacity": 0.4})

        curve_1 = ax.plot(lambda x: x ** 2, color=PURPLE_B)
        curve_2 = ax.plot_derivative_graph(curve_1)
        curves = VGroup(curve_1, curve_2)

        label_1 = ax.get_graph_label(curve_1, "x^2", x_val=-2, direction=DL)
        label_2 = ax.get_graph_label(curve_2, "2x", x_val=3, direction=RIGHT)
        labels = VGroup(label_1, label_2)

        self.add(ax, curves, labels)
plot_implicit_curve(func: Callable[[float, float], float], min_depth: int = 5, max_quads: int = 1500, **kwargs: Any) → ImplicitFunction

Creates the curves of an implicit function.

Parameters

func

The function to graph, in the form of f(x, y) = 0.

min_depth

The minimum depth of the function to calculate.

max_quads

The maximum number of quads to use.

kwargs

Additional parameters to pass into ImplicitFunction.

Examples

class ImplicitExample(Scene):
    def construct(self):
        ax = Axes()
        a = ax.plot_implicit_curve(
            lambda x, y: y * (x - y) ** 2 - 4 * x - 8, color=BLUE
        )
        self.add(ax, a)
plot_parametric_curve(function: Callable[[float], ndarray], use_vectorized: bool = False, **kwargs: Any) → ParametricFunction

A parametric curve.

Parameters

function

A parametric function mapping a number to a point in the coordinate system.

use_vectorized

Whether to pass in the generated t value array to the function. Only use this if your function supports it.

kwargs

Any further keyword arguments are passed to ParametricFunction.

Example

class ParametricCurveExample(Scene):
    def construct(self):
        ax = Axes()
        cardioid = ax.plot_parametric_curve(
            lambda t: np.array(
                [
                    np.exp(1) * np.cos(t) * (1 - np.cos(t)),
                    np.exp(1) * np.sin(t) * (1 - np.cos(t)),
                    0,
                ]
            ),
            t_range=[0, 2 * PI],
            color="#0FF1CE",
        )
        self.add(ax, cardioid)
plot_polar_graph(r_func: Callable[[float], float], theta_range: Sequence[float] | None = None, **kwargs: Any) → ParametricFunction

A polar graph.

Parameters

r_func

The function r of theta.

theta_range

The range of theta as theta_range = [theta_min, theta_max, theta_step].

kwargs

Additional parameters passed to ParametricFunction.

Examples

class PolarGraphExample(Scene):
    def construct(self):
        plane = PolarPlane()
        r = lambda theta: 2 * np.sin(theta * 5)
        graph = plane.plot_polar_graph(r, [0, 2 * PI], color=ORANGE)
        self.add(plane, graph)
plot_surface(function: Callable[[float], float], u_range: Sequence[float] | None = None, v_range: Sequence[float] | None = None, colorscale: 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]] | Sequence[tuple[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], float]] | None = None, colorscale_axis: int = 2, **kwargs: Any) → Surface | OpenGLSurface

Generates a surface based on a function.

Parameters

function

The function used to construct the Surface.

u_range

The range of the u variable: (u_min, u_max).

v_range

The range of the v variable: (v_min, v_max).

colorscale

Colors of the surface. Passing a list of colors will color the surface by z-value. Passing a list of tuples in the form (color, pivot) allows user-defined pivots where the color transitions.

colorscale_axis

Defines the axis on which the colorscale is applied (0 = x, 1 = y, 2 = z), default is z-axis (2).

kwargs

Additional parameters to be passed to Surface.

Returns

Surface

The plotted surface.

Examples

class PlotSurfaceExample(ThreeDScene):
    def construct(self):
        resolution_fa = 16
        self.set_camera_orientation(phi=75 * DEGREES, theta=-60 * DEGREES)
        axes = ThreeDAxes(x_range=(-3, 3, 1), y_range=(-3, 3, 1), z_range=(-5, 5, 1))
        def param_trig(u, v):
            x = u
            y = v
            z = 2 * np.sin(x) + 2 * np.cos(y)
            return z
        trig_plane = axes.plot_surface(
            param_trig,
            resolution=(resolution_fa, resolution_fa),
            u_range = (-3, 3),
            v_range = (-3, 3),
            colorscale = [BLUE, GREEN, YELLOW, ORANGE, RED],
            )
        self.add(axes, trig_plane)
point_to_polar(point: Point2DLike) → Point2D

Gets polar coordinates from a point.

Parameters

point

The point.

Returns

Point2D

The coordinate radius (\(r\)) and the coordinate azimuth (\(\theta\)).

polar_to_point(radius: float, azimuth: float) → Point2D

Gets a point from polar coordinates.

Parameters

radius

The coordinate radius (\(r\)).

azimuth

The coordinate azimuth (\(\theta\)).

Returns

numpy.ndarray

The point.

Examples

class PolarToPointExample(Scene):
    def construct(self):
        polarplane_pi = PolarPlane(azimuth_units="PI radians", size=6)
        polartopoint_vector = Vector(polarplane_pi.polar_to_point(3, PI/4))
        self.add(polarplane_pi)
        self.add(polartopoint_vector)
pr2pt(radius: float, azimuth: float) → ndarray

Abbreviation for polar_to_point()

pt2pr(point: np.ndarray) → Point2D

Abbreviation for point_to_polar()

slope_of_tangent(x: float, graph: ParametricFunction, **kwargs: Any) → float

Returns the slope of the tangent to the plotted curve at a particular x-value.

Parameters

x

The x-value at which the tangent must touch the curve.

graph

The ParametricFunction for which to calculate the tangent.

Returns

float

The slope of the tangent with the x axis.

Examples

ax = Axes()
curve = ax.plot(lambda x: x**2)
ax.slope_of_tangent(x=-2, graph=curve)
# -3.5000000259052038

FunctionGraph

函数图像对象:给定 f(x) 自动生成曲线,配合 Axes 使用。

继承关系

G Mobject Mobject VMobject VMobject Mobject->VMobject ParametricFunction ParametricFunction VMobject->ParametricFunction FunctionGraph FunctionGraph ParametricFunction->FunctionGraph

参数

function

—,Callable[[float], Any]

x_range

None

color

ManimColor('#FFFF00'),ParsableManimColor

快速上手

graph = axes.plot(lambda x: np.sin(x))

API 文档

class manim.FunctionGraph(function: Callable[[float], Any], x_range: tuple[float, float] | tuple[float, float, float] | None = None, color: ParsableManimColor = ManimColor('#FFFF00'), **kwargs: Any)

基类:ParametricFunction

ImplicitFunction

隐函数图像:给定 F(x, y)=0 用采样方式画出曲线,如圆锥曲线。

继承关系

G Mobject Mobject VMobject VMobject Mobject->VMobject ImplicitFunction ImplicitFunction VMobject->ImplicitFunction

参数

func

—

x_range

None,Sequence[float] | None

y_range

None,Sequence[float] | None

min_depth

5,int

max_quads

1500,int

use_smoothing

True,bool

快速上手

imp = ImplicitFunction(lambda x, y: x**2 + y**2 - 4)

API 文档

class manim.ImplicitFunction(func: Callable[[float, float], float], x_range: Sequence[float] | None = None, y_range: Sequence[float] | None = None, min_depth: int = 5, max_quads: int = 1500, use_smoothing: bool = True, **kwargs: Any)

基类:VMobject

generate_points() → Self

Initializes points and therefore the shape.

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

LinearBase

线性刻度轴的刻度策略类:刻度等距分布,Axes 默认使用。

参数

API 文档

class manim.LinearBase(scale_factor: float = 1.0)

基类:_ScaleBase

function(value: float) → float

Multiplies the value by the scale factor.

Parameters

value

Value to be multiplied by the scale factor.

inverse_function(value: float) → float

Inverse of function. Divides the value by the scale factor.

Parameters

value

value to be divided by the scale factor.

LogBase

对数刻度轴的刻度策略类:数值按对数分布,画数量级差异大的数据用。

参数

base

10,float

custom_labels

True,bool

API 文档

class manim.LogBase(base: float = 10, custom_labels: bool = True)

基类:_ScaleBase

function(value: float) → float

Scales the value to fit it to a logarithmic scale.``self.function(5)==10**5``

get_custom_labels(val_range: Iterable[float], unit_decimal_places: int = 0, **base_config: Any) → list[Integer]

Produces custom Integer labels in the form of 10^2.

Parameters

val_range

The iterable of values used to create the labels. Determines the exponent.

unit_decimal_places

The number of decimal places to include in the exponent

base_config

Additional arguments to be passed to Integer.

inverse_function(value: float) → float

Inverse of function. The value must be greater than 0

NumberLine

一维数轴:范围、步长、刻度标签、单位长度全可配,数值可视化的地基。

继承关系

G Mobject Mobject VMobject VMobject Mobject->VMobject TipableVMobject TipableVMobject VMobject->TipableVMobject Line Line TipableVMobject->Line NumberLine NumberLine Line->NumberLine

参数

x_range

None,Sequence[float] | None

length

None,float | None

unit_size

1,float

include_ticks

True,bool

tick_size

0.1,float

numbers_with_elongated_ticks

None,Iterable[float] | None

longer_tick_multiple

2,int

exclude_origin_tick

False,bool

rotation

0,float

stroke_width

2.0,float

include_tip

False,bool

tip_width

0.35,float

tip_height

0.35,float

tip_shape

None,type[ArrowTip] | None

include_numbers

False,bool

font_size

36,float

label_direction

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

label_constructor

<class 'manim.mobject.text.…,type[ManimTextLabel]

scaling

<manim.mobject.graphing.sca…,_ScaleBase

line_to_number_buff

0.25,float

decimal_number_config

None,dict | None

numbers_to_exclude

None,Iterable[float] | None

numbers_to_include

None,Iterable[float] | None

快速上手

nl = NumberLine(x_range=[-5, 5, 1])

API 文档

class manim.NumberLine(x_range: Sequence[float] | None = None, length: float | None = None, unit_size: float = 1, include_ticks: bool = True, tick_size: float = 0.1, numbers_with_elongated_ticks: Iterable[float] | None = None, longer_tick_multiple: int = 2, exclude_origin_tick: bool = False, rotation: float = 0, stroke_width: float = 2.0, include_tip: bool = False, tip_width: float = 0.35, tip_height: float = 0.35, tip_shape: type[ArrowTip] | None = None, include_numbers: bool = False, font_size: float = 36, label_direction: Point3DLike = array([ 0., -1., 0.]), label_constructor: type[ManimTextLabel] = <class 'manim.mobject.text.tex_mobject.MathTex'>, scaling: _ScaleBase = <manim.mobject.graphing.scale.LinearBase object>, line_to_number_buff: float = 0.25, decimal_number_config: dict | None = None, numbers_to_exclude: Iterable[float] | None = None, numbers_to_include: Iterable[float] | None = None, **kwargs: Any)

基类:Line

add_labels(dict_values: dict[float, str | float | VMobject], direction: Point3DLike | None = None, buff: float | None = None, font_size: float | None = None, label_constructor: type[ManimTextLabel] | None = None) → Self

Adds specifically positioned labels to the NumberLine using a dict. The labels can be accessed after creation via self.labels.

Parameters

dict_values

A dictionary consisting of the position along the number line and the mobject to be added: {1: Tex("Monday"), 3: Tex("Tuesday")}. label_constructor will be used to construct the labels if the value is not a mobject (str or float).

direction

Determines the direction at which the label is positioned next to the line.

buff

The distance of the label from the line.

font_size

The font size of the mobject to be positioned.

label_constructor

The VMobject class that will be used to construct the label. Defaults to the label_constructor attribute of the number line if not specified.

Raises

AttributeError

If the label does not have a font_size attribute, an AttributeError is raised.

add_numbers(x_values: Iterable[float] | None = None, excluding: Iterable[float] | None = None, font_size: float | None = None, label_constructor: type[SingleStringMathTex] | None = None, **kwargs: Any) → Self

Adds DecimalNumber mobjects representing their position at each tick of the number line. The numbers can be accessed after creation via self.numbers.

Parameters

x_values

An iterable of the values used to position and create the labels. Defaults to the output produced by get_tick_range()

excluding

A list of values to exclude from x_values.

font_size

The font size of the labels. Defaults to the font_size attribute of the number line.

label_constructor

The VMobject class that will be used to construct the label. Defaults to the label_constructor attribute of the number line if not specified.

add_ticks() → Self

Adds ticks to the number line. Ticks can be accessed after creation via self.ticks.

get_number_mobject(x: float, direction: Vector3D | None = None, buff: float | None = None, font_size: float | None = None, label_constructor: type[SingleStringMathTex] | None = None, **number_config: dict[str, Any]) → VMobject

Generates a positioned DecimalNumber mobject generated according to label_constructor.

Parameters

x

The x-value at which the mobject should be positioned.

direction

Determines the direction at which the label is positioned next to the line.

buff

The distance of the label from the line.

font_size

The font size of the label mobject.

label_constructor

The VMobject class that will be used to construct the label. Defaults to the label_constructor attribute of the number line if not specified.

Returns

DecimalNumber

The positioned mobject.

get_tick(x: float, size: float | None = None) → Line

Generates a tick and positions it along the number line.

Parameters

x

The position of the tick.

size

The factor by which the tick is scaled.

Returns

Line

A positioned tick.

get_tick_range() → ndarray

Generates the range of values on which labels are plotted based on the x_range attribute of the number line.

Returns

np.ndarray

A numpy array of floats represnting values along the number line.

n2p(number: float | np.ndarray) → Point3D

Abbreviation for number_to_point().

number_to_point(number: float | ndarray) → ndarray

Accepts a value along the number line and returns a point with respect to the scene. Equivalent to NumberLine @ number

Parameters

number

The value to be transformed into a coordinate. Or a list of values.

Returns

np.ndarray

A point with respect to the scene's coordinate system. Or a list of points.

Examples

>>> from manim import NumberLine
>>> number_line = NumberLine()
>>> number_line.number_to_point(0)
array([0., 0., 0.])
>>> number_line.number_to_point(1)
array([1., 0., 0.])
>>> number_line @ 1
array([1., 0., 0.])
>>> number_line.number_to_point([1, 2, 3])
array([[1., 0., 0.],
       [2., 0., 0.],
       [3., 0., 0.]])
p2n(point: Point3DLike) → float

Abbreviation for point_to_number().

point_to_number(point: Sequence[float]) → float

Accepts a point with respect to the scene and returns a float along the number line.

Parameters

point

A sequence of values consisting of (x_coord, y_coord, z_coord).

Returns

float

A float representing a value along the number line.

Examples

>>> from manim import NumberLine
>>> number_line = NumberLine()
>>> number_line.point_to_number((0, 0, 0))
np.float64(0.0)
>>> number_line.point_to_number((1, 0, 0))
np.float64(1.0)
>>> number_line.point_to_number([[0.5, 0, 0], [1, 0, 0], [1.5, 0, 0]])
array([0.5, 1. , 1.5])

NumberPlane

网格纸坐标系:Axes + 背景网格线,默认淡色网格,函数演示常用底图。

继承关系

G CoordinateSystem CoordinateSystem Mobject Mobject CoordinateSystem->Mobject VMobject VMobject Mobject->VMobject VGroup VGroup VMobject->VGroup Axes Axes VGroup->Axes NumberPlane NumberPlane Axes->NumberPlane

参数

x_range

(-7.111111111111111, 7.1111…,Sequence[float] | None

y_range

(-4.0, 4.0, 1),Sequence[float] | None

x_length

None,float | None

y_length

None,float | None

background_line_style

None,dict[str, Any] | None

faded_line_style

None,dict[str, Any] | None

faded_line_ratio

1,int

make_smooth_after_applying_functions

True,bool

快速上手

plane = NumberPlane()

API 文档

class manim.NumberPlane(x_range: Sequence[float] | None = (-7.111111111111111, 7.111111111111111, 1), y_range: Sequence[float] | None = (-4.0, 4.0, 1), x_length: float | None = None, y_length: float | None = None, background_line_style: dict[str, Any] | None = None, faded_line_style: dict[str, Any] | None = None, faded_line_ratio: int = 1, make_smooth_after_applying_functions: bool = True, **kwargs: dict[str, Any])

基类:Axes

ParametricFunction

参数方程曲线:传入 r(t) 自动采样成曲线,极坐标/物理轨迹必备。

继承关系

G Mobject Mobject VMobject VMobject Mobject->VMobject ParametricFunction ParametricFunction VMobject->ParametricFunction

参数

function

—

t_range

(0, 1)

scaling

<manim.mobject.graphing.sca…,_ScaleBase

dt

1e-08,float

discontinuities

None,Iterable[float] | None

use_smoothing

True,bool

use_vectorized

False,bool

快速上手

curve = ParametricFunction(lambda t: np.array([np.cos(t), np.sin(t), 0]), t_range=[0, TAU])

API 文档

class manim.ParametricFunction(function: Callable[[float], Point3DLike], t_range: tuple[float, float] | tuple[float, float, float] = (0, 1), scaling: _ScaleBase = <manim.mobject.graphing.scale.LinearBase object>, dt: float = 1e-08, discontinuities: Iterable[float] | None = None, use_smoothing: bool = True, use_vectorized: bool = False, **kwargs: Any)

基类:VMobject

generate_points() → Self

Initializes points and therefore the shape.

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

PolarPlane

极坐标系:同心圆 + 放射线网格,极坐标方程 r(θ) 的直接画布。

继承关系

G CoordinateSystem CoordinateSystem Mobject Mobject CoordinateSystem->Mobject VMobject VMobject Mobject->VMobject VGroup VGroup VMobject->VGroup Axes Axes VGroup->Axes PolarPlane PolarPlane Axes->PolarPlane

参数

radius_max

4.0,float

size

None,float | None

radius_step

1,float

azimuth_step

None,float | None

azimuth_units

'PI radians',str

azimuth_compact_fraction

True,bool

azimuth_offset

0,float

azimuth_direction

'CCW',str

azimuth_label_buff

0.1,float

azimuth_label_font_size

24,float

radius_config

None,dict[str, Any] | None

background_line_style

None,dict[str, Any] | None

faded_line_style

None,dict[str, Any] | None

faded_line_ratio

1,int

make_smooth_after_applying_functions

True,bool

快速上手

polar = PolarPlane()

API 文档

class manim.PolarPlane(radius_max: float = 4.0, size: float | None = None, radius_step: float = 1, azimuth_step: float | None = None, azimuth_units: str = 'PI radians', azimuth_compact_fraction: bool = True, azimuth_offset: float = 0, azimuth_direction: str = 'CCW', azimuth_label_buff: float = 0.1, azimuth_label_font_size: float = 24, radius_config: dict[str, Any] | None = None, background_line_style: dict[str, Any] | None = None, faded_line_style: dict[str, Any] | None = None, faded_line_ratio: int = 1, make_smooth_after_applying_functions: bool = True, **kwargs: Any)

基类:Axes

add_coordinates(r_values: Iterable[float] | None = None, a_values: Iterable[float] | None = None) → Self

Adds the coordinates.

Parameters

r_values

Iterable of values along the radius, by default None.

a_values

Iterable of values along the azimuth, by default None.

get_axes() → VGroup

Gets the axes.

Returns

VGroup

A pair of axes.

get_coordinate_labels(r_values: Iterable[float] | None = None, a_values: Iterable[float] | None = None, **kwargs: Any) → VDict

Gets labels for the coordinates

Parameters

r_values

Iterable of values along the radius, by default None.

a_values

Iterable of values along the azimuth, by default None.

Returns

VDict

Labels for the radius and azimuth values.

SampleSpace

概率样本空间矩形:横竖切分表示条件概率,概率论章节道具。

继承关系

G Mobject Mobject VMobject VMobject Mobject->VMobject Polygram Polygram VMobject->Polygram Polygon Polygon Polygram->Polygon Rectangle Rectangle Polygon->Rectangle SampleSpace SampleSpace Rectangle->SampleSpace

参数

height

3,float

width

3,float

fill_color

ManimColor('#444444'),ParsableManimColor

fill_opacity

1,float

stroke_width

0.5,float

stroke_color

ManimColor('#BBBBBB'),ParsableManimColor

default_label_scale_val

1,float

API 文档

class manim.SampleSpace(height: float = 3, width: float = 3, fill_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('#444444'), fill_opacity: float = 1, stroke_width: float = 0.5, stroke_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('#BBBBBB'), default_label_scale_val: float = 1)

基类:Rectangle

ThreeDAxes

三维坐标轴:x/y/z 三轴 + 可旋转视角,3D 函数绘图底座。

继承关系

G CoordinateSystem CoordinateSystem Mobject Mobject CoordinateSystem->Mobject VMobject VMobject Mobject->VMobject VGroup VGroup VMobject->VGroup Axes Axes VGroup->Axes ThreeDAxes ThreeDAxes Axes->ThreeDAxes

参数

x_range

(-6, 6, 1),Sequence[float] | None

y_range

(-5, 5, 1),Sequence[float] | None

z_range

(-4, 4, 1),Sequence[float] | None

x_length

10.5,float | None

y_length

10.5,float | None

z_length

6.5,float | None

z_axis_config

None,dict[str, Any] | None

z_normal

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

num_axis_pieces

20,int

light_source

array([-7., -9., 10.]),Point3DLike

depth

None,Any

gloss

0.5,float

快速上手

axes3d = ThreeDAxes(x_range=[-3, 3], y_range=[-3, 3], z_range=[-3, 3])

API 文档

class manim.ThreeDAxes(x_range: Sequence[float] | None = (-6, 6, 1), y_range: Sequence[float] | None = (-5, 5, 1), z_range: Sequence[float] | None = (-4, 4, 1), x_length: float | None = 10.5, y_length: float | None = 10.5, z_length: float | None = 6.5, z_axis_config: dict[str, Any] | None = None, z_normal: Vector3DLike = array([0., -1., 0.]), num_axis_pieces: int = 20, light_source: Point3DLike = array([-7., -9., 10.]), depth: Any = None, gloss: float = 0.5, **kwargs: dict[str, Any])

基类:Axes

get_axis_labels(x_label: float | str | VMobject = 'x', y_label: float | str | VMobject = 'y', z_label: float | str | VMobject = 'z') → VGroup

Defines labels for the x_axis and y_axis of the graph.

For increased control over the position of the labels, use get_x_axis_label(), get_y_axis_label(), and get_z_axis_label().

Parameters

x_label

The label for the x_axis. Defaults to MathTex for str and float inputs.

y_label

The label for the y_axis. Defaults to MathTex for str and float inputs.

z_label

The label for the z_axis. Defaults to MathTex for str and float inputs.

Returns

VGroup

A VGroup of the labels for the x_axis, y_axis, and z_axis.

Examples

class GetAxisLabelsExample(ThreeDScene):
    def construct(self):
        self.set_camera_orientation(phi=2*PI/5, theta=PI/5)
        axes = ThreeDAxes()
        labels = axes.get_axis_labels(
            Text("x-axis").scale(0.7), Text("y-axis").scale(0.45), Text("z-axis").scale(0.45)
        )
        self.add(axes, labels)
get_y_axis_label(label: float | str | VMobject, edge: Vector3DLike = array([1., 1., 0.]), direction: Vector3DLike = array([1., 1., 0.]), buff: float = 0.1, rotation: float = 1.5707963267948966, rotation_axis: Vector3DLike = array([0., 0., 1.]), **kwargs: dict[str, Any]) → Mobject

Generate a y-axis label.

Parameters

label

The label. Defaults to MathTex for str and float inputs.

edge

The edge of the y-axis to which the label will be added, by default UR.

direction

Allows for further positioning of the label from an edge, by default UR.

buff

The distance of the label from the line, by default SMALL_BUFF.

rotation

The angle at which to rotate the label, by default PI/2.

rotation_axis

The axis about which to rotate the label, by default OUT.

Returns

Mobject

The positioned label.

Examples

class GetYAxisLabelExample(ThreeDScene):
    def construct(self):
        ax = ThreeDAxes()
        lab = ax.get_y_axis_label(Tex("$y$-label"))
        self.set_camera_orientation(phi=2*PI/5, theta=PI/5)
        self.add(ax, lab)
get_z_axis_label(label: float | str | VMobject, edge: Vector3DLike = array([0., 0., 1.]), direction: Vector3DLike = array([1., 0., 0.]), buff: float = 0.1, rotation: float = 1.5707963267948966, rotation_axis: Vector3DLike = array([1., 0., 0.]), **kwargs: Any) → Mobject

Generate a z-axis label.

Parameters

label

The label. Defaults to MathTex for str and float inputs.

edge

The edge of the z-axis to which the label will be added, by default OUT.

direction

Allows for further positioning of the label from an edge, by default RIGHT.

buff

The distance of the label from the line, by default SMALL_BUFF.

rotation

The angle at which to rotate the label, by default PI/2.

rotation_axis

The axis about which to rotate the label, by default RIGHT.

Returns

Mobject

The positioned label.

Examples

class GetZAxisLabelExample(ThreeDScene):
    def construct(self):
        ax = ThreeDAxes()
        lab = ax.get_z_axis_label(Tex("$z$-label"))
        self.set_camera_orientation(phi=2*PI/5, theta=PI/5)
        self.add(ax, lab)

UnitInterval

0 到 1 的快捷数轴:概率论单位线段场景直接取用。

继承关系

G Mobject Mobject VMobject VMobject Mobject->VMobject TipableVMobject TipableVMobject VMobject->TipableVMobject Line Line TipableVMobject->Line NumberLine NumberLine Line->NumberLine UnitInterval UnitInterval NumberLine->UnitInterval

参数

unit_size

10,float

numbers_with_elongated_ticks

None,list[float] | None

decimal_number_config

None,dict[str, Any] | None

快速上手

ui = UnitInterval()

API 文档

class manim.UnitInterval(unit_size: float = 10, numbers_with_elongated_ticks: list[float] | None = None, decimal_number_config: dict[str, Any] | None = None, **kwargs: Any)

基类:NumberLine