matplotlib拟合曲线
时间: 2023-07-12 11:03:58 浏览: 77
Matplotlib可以用来拟合曲线,具体的步骤如下:
1. 导入必要的库和数据
```python
import numpy as np
import matplotlib.pyplot as plt
# 数据
x = np.array([1, 2, 3, 4, 5])
y = np.array([2, 3, 5, 6, 8])
```
2. 选择适当的函数作为拟合函数
在这里,我们选择一个二次函数作为拟合函数:
```python
def quadratic_func(x, a, b, c):
return a * x ** 2 + b * x + c
```
3. 使用`curve_fit()`函数进行拟合
```python
from scipy.optimize import curve_fit
popt, pcov = curve_fit(quadratic_func, x, y)
```
4. 绘制数据和拟合曲线
```python
plt.scatter(x, y)
plt.plot(x, quadratic_func(x, *popt), 'r-', label='fit: a=%5.3f, b=%5.3f, c=%5.3f' % tuple(popt))
plt.legend()
plt.show()
```
完整代码如下:
```python
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
# 数据
x = np.array([1, 2, 3, 4, 5])
y = np.array([2, 3, 5, 6, 8])
# 拟合函数
def quadratic_func(x, a, b, c):
return a * x ** 2 + b * x + c
# 拟合
popt, pcov = curve_fit(quadratic_func, x, y)
# 绘图
plt.scatter(x, y)
plt.plot(x, quadratic_func(x, *popt), 'r-', label='fit: a=%5.3f, b=%5.3f, c=%5.3f' % tuple(popt))
plt.legend()
plt.show()
```
阅读全文