用 Python 拟合直线
大雾实验用的电脑作图。脑子一抽想用 python 试试,结果查了半天拼凑出来了这个程序。所以当年决定不学 python 的数据处理部分真是个错误的决定。
先上代码
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
def f(x, A, B):
return A*x + B
plt.figure()
x0 = [22.71, 29.41, 34.12, 40.43, 46.13, 52.12, 57.85, 63.65, 69.69, 75.41, 81.31]
y0 = [100.22, 102.58, 104.21, 106.34, 108.27, 110.30, 112.15, 114.11, 116.06, 117.81, 119.74]
plt.scatter(x0[:], y0[:], 25, "red")
A1, B1 = optimize.curve_fit(f, x0, y0)[0]
x1 = np.arange(20, 85, 0.01)
y1 = A1*x1 + B1
plt.plot(x1, y1, "blue")
# 相关系数
r = 'r = ' + str(np.corrcoef(np.array([x0, y0]))[1][0])
# 直线表达式
expression = 'y = ' + str(A1.round(4)) + 'x' + ' + ' + str(B1.round(4))
plt.title("The relationship of temperature and pressure.")
plt.xlabel(u"t / °C")
plt.ylabel("p / kPa")
plt.figtext(0.3, 0.70, r, fontsize=15, verticalalignment="bottom", horizontalalignment="left")
plt.figtext(0.3, 0.75, expression, fontsize=15, verticalalignment="bottom", horizontalalignment="left")
plt.show()
首先你要有 python
确保你的电脑里安装了 python。Windows 去官网下一个最新的 python3,安装时记得注意要勾选 pip。Linux 自带就不多说了。
安装模块
- Windows
pip install numpy pip install matplotlib - Linux
sudo pip install numpy sudo pip install matplotlib
代码解释
f可定义为其它类型的函数,比如二次函数。拟合的时候根据f拟合。
使用round函数保留 4 位小数。
figtext函数绘制标注,其坐标是相对于图片的坐标,范围从 0 到 1。也可以用text函数,其坐标是坐标系的坐标。
° 符号非 ASCII 码,需要在字符串前加上 u。matplotlib 不支持中文标注,超级气的。懒得纠缠了,还是用英文吧。