记录Manim渲染的隐函数示例

如果方程F(x,y)=0能确定y是x的函数,那么称这种方式表示的函数是隐函数。在Manim中,很多时候需要渲染一个隐函数的图像,此时我们就可以利用Manim中的 ImplicitFunction来渲染一个隐形函数的图像,下面来介绍ImplicitFunction的相关知识。

一、核心概念与适用场景

  • ImplicitFunction 用于在二维平面上绘制满足 F(x, y) = 0 的隐式曲线,适合显式函数 y = f(x) 难以表达或无法单值表示的图形。
  • 典型场景:圆锥曲线(圆、椭圆、双曲线)、心形线双纽线、物理中的等势线/相轨迹、工程中的等值线/等高线等。

二、常用参数与含义

  • func:Callable[[float, float], float],二元函数 F(x, y),曲线为 F(x, y)=0 的零等值集。
  • x_range / y_range:序列,如 [-3, 3],定义采样矩形区域,需覆盖目标曲线。
  • color:曲线颜色,如 RED
  • min_distance:点之间的最小距离,越小越精细(计算更慢)。
  • max_quads:最大四边形数量,控制网格细分与性能上限。
  • use_smoothing:是否启用平滑,默认 True
  • delta:采样步长,影响精度与速度。
  • 常用方法:generate_points()init_points(),用于初始化点集,通常在构造时自动调用。

三、快速上手示例

3.1.画一个圆的图像

1
2
3
4
5
6
7
8
9
10
11
12
13
from manim import *

class ImplicitCircle(Scene):
def construct(self):
circle = ImplicitFunction(
lambda x, y: x**2 + y**2 - 1,
x_range=[-1.5, 1.5],
y_range=[-1.5, 1.5],
color=RED
)
label = MathTex("x^2 + y^2 = 1").next_to(circle, DOWN)
self.play(Create(circle), Write(label))
self.wait()

3.2.画一个动态椭圆图像

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from manim import *

class DynamicEllipse(Scene):
def construct(self):
a = ValueTracker(1)
b = ValueTracker(1)
ellipse = always_redraw(
lambda: ImplicitFunction(
lambda x, y: x**2 / a.get_value()**2 + y**2 / b.get_value()**2 - 1,
x_range=[-4, 4], y_range=[-3, 3], color=GREEN
)
)
param_label = always_redraw(
lambda: MathTex(
f"\\frac{{x^2}}{{{a.get_value():.1f}^2}} + \\frac{{y^2}}{{{b.get_value():.1f}^2}} = 1",
color=RED
).shift(DOWN * 1.5 + RIGHT * 1.8).scale(0.6)
)
self.add(ellipse, param_label)
self.play(a.animate.set_value(2), b.animate.set_value(1.5), run_time=3)
self.play(a.animate.set_value(3), b.animate.set_value(1), run_time=3)
self.wait()

3.3心性线

1
2
3
4
5
6
7
8
9
10
11
12
13
from manim import *

class HeartCurve(Scene):
def construct(self):
heart = ImplicitFunction(
lambda x, y: (x**2 + y**2 - 1)**3 - x**2 * y**3,
x_range=[-1.5, 1.5], y_range=[-1.2, 1.8], color=PINK
)
label = MathTex("(x^2 + y^2 - 1)^3 = x^2 y^3", color=GREEN)\
.shift(DOWN + RIGHT * 1.8).scale(0.6)
self.play(Create(heart), Write(label))
self.wait()

3.4双曲线

1
2
3
4
5
6
7
8
9
10
11
12
from manim import *

class HyperbolaDemo(Scene):
def construct(self):
axes = Axes(x_range=(-3, 3), y_range=(-2, 2))
hyperbola = ImplicitFunction(
lambda x, y: x**2 - y**2 - 1,
x_range=(-3, 3), y_range=(-2, 2), color=TEAL
)
self.play(Create(axes), Create(hyperbola))
self.wait()

3.5笛卡尔叶形线隐

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from manim import *

class ImplicitFunctionExample(Scene):
def construct(self):
# 笛卡尔叶形线隐函数方程: x^3 + y^3 - 3axy = 0 (取 a=1)
cartesian_leaf = ImplicitFunction(
lambda x, y: x**3 + y**3 - 3 * x * y, # F(x,y) = x³ + y³ - 3xy
x_range=[-2, 2],
y_range=[-2, 2],
color=BLUE,
stroke_width=3,
)

self.play(Create(cartesian_leaf))
self.wait(3)

以上示例覆盖了基础绘制、动态参数、复杂隐式曲线与常见圆锥曲线,便于快速复用与改造