使用Numpy进行线性拟合并出图
def linear_fit(x, y): # 拟合函数
# z = np.polyfit(np.log(x), np.log(y), 1)
z = np.polyfit(x, y, 1)
return [z[0], z[1]]
def plotfit(X, Y, w, b): # 散点拟合图
plt.rcParams['font.family'] = ["Times New Roman"]
matplotlib.rcParams['font.family'] = 'Times New Roman'
# 使字体同非 mathtext 字的字体,此处即 Times New Roman
matplotlib.rcParams['mathtext.default'] = 'regular'
plt.rc('font', family='times new roman')
fig, ax = plt.subplots(1, figsize=(6, 5))
plt.scatter(X, Y, c='black', label='Original Data', alpha=0.5)
plt.plot([min(X), max(X)], [w*min(X)+b, w*max(X)+b], 'red',
linewidth='1.5', label='Best Line')
plt.legend(loc=2, fontsize=14, frameon=False)
plt.xlabel('X', size=14)
plt.ylabel('Y', fontsize=14)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
# plt.xscale('log')
# plt.yscale('log')
# plt.tight_layout()
# plt.show()
plt.savefig('拟合结果.png', dpi=300)
代码如下(示例):
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
def linear_fit(x, y):
# z = np.polyfit(np.log(x), np.log(y), 1)
z = np.polyfit(x, y, 1)
return [z[0], z[1]]
def plotfit(X, Y, w, b): # 散点拟合图
plt.rcParams['font.family'] = ["Times New Roman"]
matplotlib.rcParams['font.family'] = 'Times New Roman'
# 使字体同非 mathtext 字的字体,此处即 Times New Roman
matplotlib.rcParams['mathtext.default'] = 'regular'
plt.rc('font', family='times new roman')
fig, ax = plt.subplots(1, figsize=(6, 5))
plt.scatter(X, Y, c='black', label='Original Data', alpha=0.5)
plt.plot([min(X), max(X)], [w*min(X)+b, w*max(X)+b], 'red',
linewidth='1.5', label='Best Line')
plt.legend(loc=2, fontsize=14, frameon=False)
plt.xlabel('X', size=14)
plt.ylabel('Y', fontsize=14)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
# plt.xscale('log')
# plt.yscale('log')
# plt.tight_layout()
# plt.show()
plt.savefig('拟合结果.png', dpi=300)
# 先预设一个结果,假定拟合的结果为 y=6x+10
X = np.linspace(0, 10, 100)
a = 6
b = 10
Y = list(map(lambda x: a * x + b, X))
# 增加噪声,制造数据
Y_noise = list(map(lambda y: y + np.random.randn() * 10, Y))
#拟合
p = linear_fit(X, Y_noise)
plotfit(X, Y_noise, p[0], p[1])