matplotlib.pyplot如何让折线显得平滑
时间: 2023-11-05 11:39:06 浏览: 203
可以使用平滑曲线拟合算法,如样条插值法(spline interpolation)、局部加权回归(Locally Weighted Regression,LWR)等。这些算法可以通过SciPy库中的interpolate模块来实现。具体步骤如下:
1. 导入必要的库
```python
import numpy as np
from scipy.interpolate import make_interp_spline
import matplotlib.pyplot as plt
```
2. 准备数据
```python
x = np.array([1, 2, 3, 4, 5])
y = np.array([2, 4, 6, 8, 10])
```
3. 使用样条插值法生成平滑曲线
```python
x_new = np.linspace(x.min(), x.max(), 300)
spl = make_interp_spline(x, y, k=3)
y_smooth = spl(x_new)
```
其中,`k`参数表示样条插值函数的阶数,一般取3或4。
4. 绘制原始数据和平滑曲线
```python
plt.plot(x, y, 'o', label='原始数据')
plt.plot(x_new, y_smooth, label='平滑曲线')
plt.legend()
plt.show()
```
完整代码如下:
```python
import numpy as np
from scipy.interpolate import make_interp_spline
import matplotlib.pyplot as plt
x = np.array([1, 2, 3, 4, 5])
y = np.array([2, 4, 6, 8, 10])
x_new = np.linspace(x.min(), x.max(), 300)
spl = make_interp_spline(x, y, k=3)
y_smooth = spl(x_new)
plt.plot(x, y, 'o', label='原始数据')
plt.plot(x_new, y_smooth, label='平滑曲线')
plt.legend()
plt.show()
```
运行结果如下:
![smooth_line](https://user-images.githubusercontent.com/59767264/132356272-9c9920f8-8aa1-49cc-af23-7620f7d8dbd8.png)
阅读全文