class Node(Scene):
def construct(self):
创建坐标轴
axes = Axes(
x_range=[0, 10, 1], # 时间范围
y_range=[0, 10, 1], # 胆固醇范围
axis_config={"color": BLUE},
x_length=8,
y_length=5,
tips=True
)
axes.add_coordinates(font_size=12)
# 定义胆固醇变化的函数
def cholesterol_func(x):
return 5 + 2 * np.sin(x / 5) + np.sin(x/10)
# 绘制胆固醇变化的曲线
cholesterol_graph = axes.plot(cholesterol_func, color=RED)
def counterfactual_func(x):
return 5 - 2 * np.sin(x / 5)
counterfactual_graph = axes.plot(counterfactual_func, color=GREEN)
# 创建坐标轴标签
# a = axes.axis_labels()
x_label = Text("时间 (月)",font_size=12)
y_label = Text("胆固醇 (mmol/L)",font_size=12)
x_label.next_to(axes.x_axis.get_end(), DOWN)
y_label.next_to(axes.y_axis.get_end(), LEFT)
text_now = Text("当前时间点", font_size=12, color=RED).next_to(x_label, DOWN)
# 创建曲线标签
equation_text = Text("某人胆固醇水平随时间变化的曲线", color=YELLOW, font_size=20).next_to(cholesterol_graph, UP).shift(UP)
# 显示坐标轴、标签和曲线
self.play(Create(axes), Write(x_label), Write(y_label), Write(text_now))
self.play(Write(equation_text))
# 动画显示胆固醇变化的过程
time_range = np.linspace(0, 10, 100) # 时间点
cholesterol_points = [cholesterol_func(x) for x in time_range]
# 创建一个 Dot 用于跟踪胆固醇水平
dot = Dot(color=YELLOW).move_to(axes.c2p(0, cholesterol_func(0)))
dot_text = Text("未使用药物", font_size=12, color=RED).next_to(dot, RIGHT)
trajectory = Line(start=dot.get_center(), end=dot.get_center(), color=YELLOW)
dot2 = Dot(color=RED).move_to(axes.c2p(0, counterfactual_func(0)))
dot_text2 = Text("使用药物", font_size=12, color=RED).next_to(dot2, RIGHT)
trajectory2 = Line(start=dot2.get_center(), end=dot2.get_center(), color=RED)
# 添加 Dot 到场景
self.play(Create(dot),Create(trajectory),Create(dot_text),Create(dot2),Create(trajectory2),Create(dot_text2))
# 动画:点在曲线上的移动
for t in time_range:
# dot.move_to(axes.c2p(t, cholesterol_func(t)))
# # trajectory.add_points_as_corners([dot.get_center()])
# self.play(dot.animate.move_to(axes.c2p(t, cholesterol_func(t))), run_time=0.1)
new_position = axes.c2p(t, cholesterol_func(t))
new_text_position = axes.c2p(t, cholesterol_func(t) + 0.5)
dot.move_to(new_position)
dot_text.move_to(new_text_position, RIGHT)
trajectory.add_points_as_corners([new_position]) # 添加轨迹点
self.play(dot.animate.move_to(new_position), dot_text.animate.move_to(new_text_position),run_time=0.1)
new_position2 = axes.c2p(t, counterfactual_func(t))
new_text_position2 = axes.c2p(t, counterfactual_func(t) + 0.5)
dot2.move_to(new_position2)
dot_text2.move_to(new_text_position2, RIGHT)
trajectory2.add_points_as_corners([new_position2]) # 添加轨迹点
self.play(dot2.animate.move_to(new_position2), dot_text2.animate.move_to(new_text_position2),run_time=0.1)
# 等待查看结果
# self.wait(1)
# self.play(Create(cholesterol_graph))
self.wait(2)
使用manim做出点在坐标系中动态移动的动画
最新推荐文章于 2025-12-04 22:56:41 发布
1677

被折叠的 条评论
为什么被折叠?



