在Python中,如何使用合适的库(如Matplotlib或Seaborn)来绘制散点图并对其进行光滑的曲线拟合?
时间: 2024-10-19 14:17:33 浏览: 203
在Python中,使用Matplotlib库来绘制散点图非常直观,而进行光滑的曲线拟合则可以借助scipy或statsmodels库。以下是基本步骤:
1. **导入必要的库**:
```python
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from scipy.signal import savgol_filter
```
2. **创建数据(假设我们有随机生成的散点数据)**:
```python
np.random.seed(0) # 设置随机种子以保证结果一致
x = np.linspace(0, 10, 50)
y = 2 * x + 3 + np.random.normal(0, 2, len(x)) # 随机噪声使得数据不是完美的线性关系
```
3. **绘制原始散点图**:
```python
plt.scatter(x, y, color='black')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Original Scatter Plot')
plt.grid(True)
plt.show()
```
4. **曲线拟合(线性回归为例,使用`curve_fit`)**:
```python
def linear_func(p, x):
return p[0] * x + p[1]
params, _ = curve_fit(linear_func, x, y) # 参数估计
y_fitted = linear_func(params, x)
plt.plot(x, y_fitted, 'r', label='Fitted Line')
plt.legend()
```
5. **进行平滑处理(使用Savitzky-Golay滤波器)**:
```python
y_smoothed = savgol_filter(y, window_length=51, polyorder=2) # 窗口长度和多项式阶数可根据需要调整
```
6. **最后绘制平滑后的曲线**:
```python
plt.plot(x, y_smoothed, 'g', label='Smoothed Curve')
plt.legend()
plt.show()
```
以上代码演示了如何用Matplotlib进行基本的散点图绘制和线性回归拟合,以及使用Savitzky-Golay滤波器进行平滑处理。
阅读全文
相关推荐


















