Manim 0.12.0线性回归动画中如何将CSV坐标绘制成散点
解决方案
Manim 0.12.0版本的NumberPlane提供内置坐标转换方法c2p(),传入你读取的原始x、y数值即可直接得到对应画布位置,无需手动换算比例。
完整修改后的可用代码如下:
from manim import * def get_coords_from_csv(Filename): import csv coords = [] with open(f'{Filename}.csv', 'r') as csvFile: reader = csv.reader(csvFile) for row in reader: # 处理csv行末多余的逗号和空格 x = float(row[0].strip()) y = float(row[1].strip()) coords.append([x,y]) return coords class graphing(Scene): def construct(self): Simp = Text("Simple linear regression", font_size = 30, color = RED) plane = NumberPlane( x_range = [0, 30000, 5000], x_length = 10, y_range = [0, 1000, 200], y_length = 7).scale(0.7).add_coordinates() ylabel = Text("CoS", font_size = 20).next_to(plane, LEFT, buff = 0.3) xlabel = Text("Revenue", font_size = 20).next_to(plane, DOWN, buff = 0.2) lm = plane.plot(lambda x : -0.3511 + 0.0318 * x, x_range = [0, 30000], color = WHITE) func_label = MathTex(r"fX= \theta_{0}+\theta_{1}*x").scale(0.6).next_to(lm, RIGHT, buff=0.5) # ===== 散点绘制代码 ===== # 读取csv数据,替换为你的csv文件名(不需要加.csv后缀) coords = get_coords_from_csv("你的文件名") # 生成散点组 scatter_points = VGroup() for x,y in coords: dot = Dot( point=plane.c2p(x, y), radius=0.07, # 可自定义圆点大小 color=YELLOW # 可自定义圆点颜色 ) scatter_points.add(dot) # 动画流程 self.play(Create(Simp), run_time = 0.7) self.play(Simp.animate.to_edge(UP)) self.play(DrawBorderThenFill(plane)) # 散点创建动画,可根据需求调整出现顺序 self.play(Create(scatter_points), run_time=1) self.play(Create(lm), run_time = 1) self.play(Create(VGroup(ylabel, xlabel, func_label)), run_time = 1) self.wait(2)
补充说明
- 代码已修正原始代码中play方法连写的语法错误,可直接运行
- 散点的大小、颜色、出现时机都可根据需求调整,若需要散点在回归线之后展示,只需把散点的Create动画移到回归线绘制语句之后即可
内容的提问来源于stack exchange,提问作者Biep-boop
相关产品推荐
相关产品推荐

