【Python】GUI设计实现画图和回归

Python基础编程题:

编写程序,选择自己5个朋友姓名、体重和身高存入字典中,
通过GUI设计一个输入框和一个按钮,可以加入更多的朋友的内容;
设计一个按钮,按钮点击可以画出体重柱形图;
还有一个按钮,点击可以对身高和体重进行OLS回归,并画出散点图和拟合图。

'''
编写程序,选择自己5个朋友姓名、体重和身高存入字典中,
通过GUI设计一个输入框和一个按钮,可以加入更多的朋友的内容;
设计一个按钮,按钮点击可以画出体重柱形图;
还有一个按钮,点击可以对身高和体重进行OLS回归,并画出散点图和拟合图。
'''
import tkinter as tk
import tkinter.messagebox
import matplotlib.pyplot as plt
import re
from sklearn.linear_model import LinearRegression
import numpy as np

root = tk.Tk()
root.title('朋友的体重的柱形图以及身高体重的线性关系')
root.geometry('450x250+300+250')

friends = {'小1': [50, 170], '小2': [65, 178], '小3': [80, 162], '小4': [96, 188], '小5': [42, 150]}
label = tk.Label(root, text='在这里输入你的朋友的信息,\n分别为姓名,体重(kg),身高(m),用中文逗号隔开')
label.place(x=50,y=0)
entry = tk.Entry(root)
entry.place(x=100,y=50)
def add_friends():
    global friends
    content = entry.get()
    pattern = '.*?,\d*.?\d*,\d*.?\d*'
    if not re.match(pattern, content):
        tkinter.messagebox.showinfo('错误报告', '格式不对,重新输入')
    else:
        name, weight, height = content.split(',')
        friends[name] = [float(weight), float(height)]

def draw_bar():
    global friends
    weight, height = [], []
    new_friends = {}
    for key in friends:
        weight.append(friends[key][0])
        height.append(friends[key][1])
        new_friends[key] = friends[key][0]
    plt.figure(figsize=(12,8))
    plt.rcParams['font.sans-serif']='SimHei'
    plt.bar(new_friends.keys(), new_friends.values())
    plt.title('体重柱形图')
    plt.show()

def draw_OLS():
    global friends
    weight, height = [], []
    for key in friends:
        weight.append(friends[key][0])
        height.append(friends[key][1])
    plt.figure(figsize=(12,8))
    plt.rcParams['font.sans-serif']='SimHei'
    plt.scatter(height, weight, c='r', marker='*')
    weight = np.array(weight)
    weight = weight.reshape(-1, 1)
    height = np.array(height)
    height = height.reshape(-1, 1)
    model = LinearRegression()
    result = model.fit(height, weight)
    alpha = result.intercept_
    beta = result.coef_[0]
    
    x = np.linspace(min(height), max(height), 1000)
    y = model.predict(x)  # 这是直接用函数的方法
#     y = alpha + beta * x  # 这是取参数自己算的方法
    plt.plot(x, y)
    
    
    plt.title('体重和身高散点图')
    plt.show()
    
button0 = tk.Button(root, text='加入朋友', command=add_friends)
button1 = tk.Button(root, text='画柱形图', command=draw_bar)
button2 = tk.Button(root, text='画散点拟合图', command=draw_OLS)

button0.place(x=125,y=75)
button1.place(x=125,y=115)
button2.place(x=125,y=155)

root.mainloop()

在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

strangequark

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值