python散点图拟合曲线如何求拟合_python散点图最佳拟合直线的代码

本文展示了如何使用Python的numpy和matplotlib库从CSV文件读取数据,绘制散点图,并通过polyfit函数求得散点图的最佳拟合直线。代码包括了从数据中计算斜率、截距、决定系数以及误差界限的过程,并在图表上显示了拟合曲线及其误差范围。
摘要由CSDN通过智能技术生成

你可以用numpy的polyfit。我使用以下(您可以安全地删除关于确定系数和误差界限的位,我只是认为它看起来不错):#!/usr/bin/python3

import numpy as np

import matplotlib.pyplot as plt

import csv

with open("example.csv", "r") as f:

data = [row for row in csv.reader(f)]

xd = [float(row[0]) for row in data]

yd = [float(row[1]) for row in data]

# sort the data

reorder = sorted(range(len(xd)), key = lambda ii: xd[ii])

xd = [xd[ii] for ii in reorder]

yd = [yd[ii] for ii in reorder]

# make the scatter plot

plt.scatter(xd, yd, s=30, alpha=0.15, marker='o')

# determine best fit line

par = np.polyfit(xd, yd, 1, full=True)

slope=par[0][0]

intercept=par[0][1]

xl = [min(xd), max(xd)]

yl = [slope*xx + intercept for xx in xl]

# coefficient of determination, plot text

v

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值