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()
复制代码

 

posted @   神行乌龟  阅读(455)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· NetPad:一个.NET开源、跨平台的C#编辑器
点击右上角即可分享
微信分享提示