matplotlib绘制平滑曲线
时间: 2024-08-24 21:00:28 浏览: 66
在Python的matplotlib库中,绘制平滑曲线通常需要对数据进行插值处理,以便得到更平滑的线条。你可以使用`interpolate()`函数或者Pandas库提供的`resample`和`rolling`功能来实现这个目的。以下是基本步骤:
1. 导入所需模块:首先导入`numpy`、`pandas`和`matplotlib.pyplot`。
```python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
```
2. 准备数据:创建一个包含你需要平滑的数据序列。
```python
x = np.linspace(0, 10, 100) # 生成从0到10的等差数组,共100个点
y_noisy = np.sin(x) + np.random.normal(0, 0.5, len(x)) # 添加噪声
```
3. 数据预处理:使用Pandas的`rolling`或`resample`对数据进行平滑处理。
```python
# 使用rolling平均窗口对数据进行平滑
y_smoothed_rolling = y_noisy.rolling(window=10).mean() # 窗口大小可以根据需求调整
# 或者使用线性插值
from scipy.interpolate import interp1d
f_interpolator = interp1d(x, y_noisy)
x_new = np.linspace(x.min(), x.max(), 200) # 创建新的均匀分布的x轴
y_smoothed_interp = f_interpolator(x_new)
```
4. 绘制曲线:最后,使用matplotlib将原始数据和平滑后的数据分别绘制出来。
```python
plt.plot(x, y_noisy, label='Original Data')
plt.plot(x_new, y_smoothed_rolling, label='Smoothed with Rolling Mean', linestyle='-')
plt.plot(x_new, y_smoothed_interp, label='Smoothed with Linear Interpolation', linestyle='--')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.legend()
plt.show()
```
阅读全文
相关推荐

















