python中散点图最佳拟合直线的代码 [英] Code for best fit straight line of a scatter plot in python

查看:803
本文介绍了python中散点图最佳拟合直线的代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的代码,用于在我的文本文件中绘制数据.我打开的文件包含两列.左列是 x 坐标,右列是 y 坐标.该代码创建了 x 与 y 的散点图.我需要一个代码来绘制一条最适合散点图中数据的线,但没有一个内置的 pylab 函数对我有用.

from matplotlib import *从 pylab 导入 *with open('file.txt') as f:data = [line.split() for line in f.readlines()]out = [(float(x), float(y)) for x, y in data]因为我进了:分散(我[0],我[1])xlabel('X')ylabel('Y')title('我的标题')表演()

解决方案

这个优秀答案的单行版本绘制最佳拟合线是:

plt.plot(np.unique(x), np.poly1d(np.polyfit(x, y, 1))(np.unique(x)))

使用 np.unique(x) 而不是 x 可以处理 x 未排序或具有重复值的情况.

Below is my code for scatter plotting the data in my text file. The file I am opening contains two columns. The left column is x coordinates and the right column is y coordinates. the code creates a scatter plot of x vs. y. I need a code to overplot a line of best fit to the data in the scatter plot, and none of the built in pylab function have worked for me.

from matplotlib import *
from pylab import *

with open('file.txt') as f:
   data = [line.split() for line in f.readlines()]
   out = [(float(x), float(y)) for x, y in data]
for i in out:
   scatter(i[0],i[1])
   xlabel('X')
   ylabel('Y')
   title('My Title')
show()

解决方案

A one-line version of this excellent answer to plot the line of best fit is:

plt.plot(np.unique(x), np.poly1d(np.polyfit(x, y, 1))(np.unique(x)))

Using np.unique(x) instead of x handles the case where x isn't sorted or has duplicate values.

这篇关于python中散点图最佳拟合直线的代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆