<think>我们使用Manim库来绘制伽马分布的概率密度函数图像。伽马分布的概率密度函数为:
$$ f(x; \alpha, \beta) = \frac{\beta^\alpha x^{\alpha-1} e^{-\beta x}}{\Gamma(\alpha)} \quad \text{for } x \geq 0 $$
其中,$\alpha>0$是形状参数,$\beta>0$是速率参数,$\Gamma(\alpha)$是伽马函数。
步骤:
1. 导入必要的模块:`manim`库中的`Scene`、`Axes`等,以及科学计算库`numpy`和`scipy.stats`(用于计算伽马分布的概率密度函数)。
2. 创建坐标轴。
3. 定义伽马分布的参数(例如,设置几个不同的参数组合来展示不同的形状)。
4. 使用`scipy.stats.gamma`生成概率密度函数的数据点。
5. 在坐标轴上绘制曲线。
注意:由于Manim社区版(CE)和经典版(旧版)的API有差异,这里我们使用Manim CE(0.17.3)的语法。
示例代码:
```python
from manim import *
import numpy as np
from scipy.stats import gamma
class GammaDistribution(Scene):
def construct(self):
# 创建坐标轴
axes = Axes(
x_range=[0, 10, 1],
y_range=[0, 0.5, 0.1],
axis_config={"color": BLUE},
)
axes_labels = axes.get_axis_labels(x_label="x", y_label="f(x)")
# 设置不同的参数组合:形状参数alpha,速率参数beta(注意scipy中gamma分布参数为形状参数a=alpha,尺度参数scale=1/beta)
# 这里我们使用形状参数k=alpha,尺度参数theta=1/beta
params = [
{"alpha": 1, "beta": 1}, # 指数分布
{"alpha": 2, "beta": 1},
{"alpha": 3, "beta": 1},
{"alpha": 2, "beta": 2},
]
colors = [RED, GREEN, YELLOW, PURPLE]
# 创建图例
legend = VGroup()
# 绘制每条曲线
graphs = VGroup()
for i, (param, color) in enumerate(zip(params, colors)):
alpha = param["alpha"]
beta = param["beta"]
# 注意:scipy中gamma分布参数为形状参数a=alpha,尺度参数scale=1/beta
dist = gamma(a=alpha, scale=1/beta)
# 定义函数,使用scipy的pdf方法
graph = axes.plot(
lambda x: dist.pdf(x),
color=color,
x_range=[0, 10, 0.1]
)
graphs.add(graph)
# 添加图例项
label = MathTex(rf"\alpha={alpha},\beta={beta}", color=color).scale(0.7)
# 将标签放在图的末尾(取x=9处的点,但可能超出范围,所以取x=min(9, 10))
point = axes.c2p(9, dist.pdf(9))
dot = Dot(point=point, color=color)
label.next_to(dot, RIGHT, buff=0.1)
legend_item = VGroup(dot, label)
legend.add(legend_item)
# 排列图例
legend.arrange(DOWN, aligned_edge=LEFT, buff=0.2).to_corner(UR)
# 添加标题
title = Text("伽马分布的概率密度函数", font_size=24).to_edge(UP)
# 动画展示
self.play(Create(axes), Write(axes_labels), Write(title))
self.wait(0.5)
for graph, legend_item in zip(graphs, legend):
self.play(Create(graph), run_time=2)
self.play(FadeIn(legend_item))
self.wait(0.5)
self.wait(2)
```
注意:
- 上述代码中,我们使用了`scipy.stats.gamma`来计算概率密度函数的值。确保你的环境中安装了`scipy`。
- 图例部分,我们为每条曲线创建了一个标签,并放置在右上角。
- 动画中,我们依次绘制每条曲线并同时显示对应的图例项。
运行此场景的命令(假设文件名为`gamma_distribution.py`):
```
manim -pql gamma_distribution.py GammaDistribution
```
如果你需要更高分辨率的输出,可以使用`-p`选项预览,或使用`-pqh`获得高清质量。
相关问题:
1. 如何在Manim中绘制其他概率分布(如正态分布、泊松分布)?
2. Manim中如何自定义坐标轴的刻度和标签?
3. 如何将Manim动画导出为GIF或视频文件?</think>在 Manim 中绘制伽马分布图像需要结合概率密度函数公式和绘图功能,以下是详细步骤:
### 伽马分布概率密度函数
伽马分布的概率密度函数为:
$$ f(x; \alpha, \beta) = \frac{\beta^\alpha x^{\alpha-1} e^{-\beta x}}{\Gamma(\alpha)} \quad \text{当 } x \geq 0 $$
其中:
- $\alpha > 0$ 为形状参数
- $\beta > 0$ 为速率参数
- $\Gamma(\alpha)$ 是伽马函数
### Manim 实现代码
```python
from manim import *
import numpy as np
from scipy.special import gamma as gamma_func
class GammaDistribution(Scene):
def construct(self):
# 创建坐标系
axes = Axes(
x_range=[0, 10, 1],
y_range=[0, 0.5, 0.1],
axis_config={"color": BLUE},
tips=False,
)
axes_labels = axes.get_axis_labels(x_label="x", y_label="f(x)")
# 定义伽马分布函数
def gamma_pdf(x, alpha, beta):
if x <= 0:
return 0
return (beta**alpha * x**(alpha-1) * np.exp(-beta*x)) / gamma_func(alpha)
# 创建不同参数的曲线
params = [
(1, 1, RED), # α=1, β=1 (指数分布)
(2, 1, GREEN), # α=2, β=1
(3, 1, YELLOW), # α=3, β=1
(2, 2, PURPLE) # α=2, β=2
]
curves = VGroup()
labels = VGroup()
for alpha, beta, color in params:
# 绘制曲线
curve = axes.plot(
lambda x: gamma_pdf(x, alpha, beta),
color=color,
x_range=[0.01, 10, 0.1] # 避开x=0
)
curves.add(curve)
# 添加参数标签
label = MathTex(
rf"\alpha={alpha},\beta={beta}",
color=color
).scale(0.7)
labels.add(label)
# 排列标签
labels.arrange(DOWN, aligned_edge=LEFT, buff=0.2).to_corner(UR)
# 添加标题
title = Text("伽马分布", font_size=24).to_edge(UP)
formula = MathTex(
r"f(x;\alpha,\beta) = \frac{\beta^\alpha x^{\alpha-1} e^{-\beta x}}{\Gamma(\alpha)}"
).next_to(title, DOWN)
# 动画序列
self.play(Create(axes), Write(axes_labels))
self.play(Write(title), Write(formula))
for curve, label in zip(curves, labels):
self.play(Create(curve), run_time=2)
self.play(Write(label))
self.wait(0.5)
self.wait(3)
```
### 关键步骤说明
1. **坐标系设置**:
- 使用`Axes`创建直角坐标系
- 设置合理的x/y范围(伽马分布定义域 $x \geq 0$)
2. **概率密度函数实现**:
- 使用`scipy.special.gamma`计算伽马函数
- 处理 $x=0$ 的边界情况(当 $\alpha < 1$ 时函数值趋近无穷)
3. **多曲线绘制**:
- 不同参数组合展示分布形态变化
- $\alpha$ 控制形状,$\beta$ 控制尺度
4. **数学公式渲染**:
- 使用`MathTex`显示分布公式
- 参数标签动态跟随曲线
### 运行命令
```bash
manim -pql gamma_plot.py GammaDistribution
```
添加`-p`选项预览效果,`-qh`生成高清视频
### 效果增强建议
1. 添加分布特性标注:
```python
# 在动画中添加注释
remark = Text("α控制形状,β控制尺度", font_size=18).to_edge(DOWN)
self.play(Write(remark))
```
2. 显示曲线下面积(概率积分):
```python
area = axes.get_area(curve, [0, 10], color=color, opacity=0.3)
self.play(FadeIn(area))
```
3. 添加动态参数调节滑块(使用`ValueTracker`):
```python
alpha_tracker = ValueTracker(2.0)
curve = always_redraw(lambda: axes.plot(
lambda x: gamma_pdf(x, alpha_tracker.get_value(), 1)
))
self.play(alpha_tracker.animate.set_value(5), run_time=3)
```