1 Manim例子一
最近接触到manim,觉得挺有趣的,来玩一玩把。如下是一个使用manim画的高斯分布的动画。
from manim import *
import numpy as np
class GaussianDistribution(Scene):
def construct(self):
# 创建坐标系
axes = Axes(
x_range=[-4, 4, 1],
y_range=[0, 0.5, 0.1],
axis_config={"color": BLUE},
)
# 添加坐标轴标签
labels = axes.get_axis_labels(
x_label=MathTex("x"),
y_label=MathTex("P(x)")
)
# 定义高斯分布函数
def gaussian(x, mu=0, sigma=1):
return (1 / (sigma * np.sqrt(2 * np.pi))) * np.exp(-0.5 * ((x - mu) / sigma) ** 2)
# 创建高斯分布曲线
gaussian_curve = axes.plot(
lambda x: gaussian(x),
color=YELLOW,
x_range=[-4, 4]
)
# 创建曲线方程标签
equation = MathTex(
"P(x) = \\frac{1}{\\sigma\\sqrt{2\\pi}} e^{-\\frac{(x-\\mu)^2}{2\\sigma^2}}",
color=YELLOW
).scale(0.8).to_edge(UP)
# 添加动画
self.play(Create(axes), Write(labels))
self.play(Write(equation))
self.play(Create(gaussian_curve), run_time=2)
# 添加说明文字
description = Text(
"高斯分布(正态分布):μ=0, σ=1",
font="SimSun"
).scale(0.5).to_edge(DOWN)
self.play(Write(description))
# 添加动态效果:显示不同参数的高斯分布
sigma_values = [0.5, 1, 2]
colors = [RED, YELLOW, GREEN]
for sigma, color in zip(sigma_values, colors):
new_curve = axes.plot(
lambda x: gaussian(x, sigma=sigma),
color=color,
x_range=[-4, 4]
)
new_description = Text(
f"高斯分布:μ=0, σ={sigma}",
font="SimSun"
).scale(0.5).to_edge(DOWN)
self.play(
Transform(gaussian_curve, new_curve),
Transform(description, new_description),
run_time=1.5
)
self.wait(0.5)
self.wait(2)
if __name__ == "__main__":
with tempconfig({
"preview": True,
"quality": "medium_quality",
"format": "mp4"
}):
scene = GaussianDistribution()
scene.render()```
```bash
2动画效果