python大作业-图形化关于散点图拟合曲线
import numpy as np import tkinter as tk from tkinter import messagebox from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg from matplotlib.figure import Figure def plot_data(x, y, ax): # 绘制散点图 ax.scatter(x, y, label="Data Points") def plot_fit(x, y, ax): # 多项式函数拟合 coef = np.polyfit(x, y, 3) poly = np.poly1d(coef) x_fit = np.linspace(x.min(), x.max(), 100) y_fit = poly(x_fit) # 绘制拟合曲线 ax.plot(x_fit, y_fit, label="Curve Fit") # 添加图例和标签 ax.legend() ax.set_xlabel("X") ax.set_ylabel("Y") def plot_curve(): # 从输入框中获取x和y数据 x_str = entry_x.get().split(",") y_str = entry_y.get().split(",") # 检查输入的数据是否合法 if len(x_str) != len(y_str): messagebox.showerror("错误", "x和y数据长度不一致!") return try: x = np.array([float(i) for i in x_str]) y = np.array([float(i) for i in y_str]) except ValueError: messagebox.showerror("错误", "请输入合法的数值!") return # 清空画布上的内容 fig.clear() # 绘制散点图和拟合曲线 ax = fig.add_subplot(111) plot_data(x, y, ax) plot_fit(x, y, ax) # 更新画布 canvas.draw() root = tk.Tk() root.title("曲线拟合") # 添加标签和输入框 label_x = tk.Label(root, text="x数据:") label_x.grid(row=0, column=0) entry_x = tk.Entry(root) entry_x.grid(row=0, column=1) label_y = tk.Label(root, text="y数据:") label_y.grid(row=1, column=0) entry_y = tk.Entry(root) entry_y.grid(row=1, column=1) # 添加按钮 button = tk.Button(root, text="绘制曲线", command=plot_curve) button.grid(row=2, column=1, pady=10) # 添加画布 fig = Figure() canvas = FigureCanvasTkAgg(fig, master=root) canvas.get_tk_widget().grid(row=3, column=0, columnspan=2) tk.mainloop()
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· NetPad:一个.NET开源、跨平台的C#编辑器