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 @ 2023-05-15 22:00  神行乌龟  阅读(504)  评论(0)    收藏  举报