Axes 负责把数学坐标映射到画布坐标,axes.plot() 接收函数直接生成曲线。示例同时画出 sin 和 cos,并用 get_graph_label() 给两条曲线加公式标注,是函数图像类文章的起点。

完整代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
from manim import *
import numpy as np
class SinAndCosFunctionPlot(Scene):
def construct(self):
axes = Axes(
x_range=[-10, 10.3, 1],
y_range=[-1.5, 1.5, 1],
x_length=10,
axis_config={"color": GREEN},
x_axis_config={
"numbers_to_include": np.arange(-10, 10.01, 2),
"numbers_with_elongated_ticks": np.arange(-10, 10.01, 2),
},
tips=False,
)
axes_labels = axes.get_axis_labels()
sin_graph = axes.plot(lambda x: np.sin(x), color=BLUE)
cos_graph = axes.plot(lambda x: np.cos(x), color=RED)
sin_label = axes.get_graph_label(
sin_graph, "\\sin(x)", x_val=-10, direction=UP / 2
)
cos_label = axes.get_graph_label(cos_graph, label="\\cos(x)")
vert_line = axes.get_vertical_line(
axes.i2gp(TAU, cos_graph), color=YELLOW, line_func=Line
)
line_label = axes.get_graph_label(
cos_graph, r"x=2\pi", x_val=TAU, direction=UR, color=WHITE
)
plot = VGroup(axes, sin_graph, cos_graph, vert_line)
labels = VGroup(axes_labels, sin_label, cos_label, line_label)
self.play(*[FadeIn(_o) for _o in [plot, labels]], run_time=1.0)
self.wait(1)
self.wait(3.60)

演示视频

下载 Python 脚本

要点

  • x_range / y_range 的第三个值是刻度步长,tips=False 可去掉轴箭头
  • get_graph_label() 的 x_val 决定公式标签挂在曲线哪个位置
  • 公式里的 \sin 需要 LaTeX 环境;本项目用 TinyTeX + MiKTeX 的 dvisvgm 渲染

代码来源:Manim Community 官方 Example Gallery 示例 SinAndCosFunctionPlot,已在 Manim CE 0.20.1 实跑验证并生成上方视频。