使用PyPlot绘制平滑曲线

179 投票
8 回答
391269 浏览
提问于 2025-04-16 13:33

我有一个简单的脚本,可以画出一个图表:

import matplotlib.pyplot as plt
import numpy as np

T = np.array([6, 7, 8, 9, 10, 11, 12])
power = np.array([1.53E+03, 5.92E+02, 2.04E+02, 7.24E+01, 2.72E+01, 1.10E+01, 4.70E+00])

plt.plot(T,power)
plt.show()

现在这个图的线是直接从一个点连到另一个点,看起来还不错,但我觉得可以更好。我想要的是让这些点之间的线变得更平滑。在Gnuplot中,我会用 smooth cplines 来实现。

在PyPlot中有没有简单的方法可以做到这一点?我找到了一些教程,但它们看起来都挺复杂的。

8 个回答

26

可以查看scipy.interpolate的文档,里面有一些示例。

下面这个例子展示了如何使用它进行线性插值和三次样条插值:

import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate import interp1d

# Define x, y, and xnew to resample at.
x = np.linspace(0, 10, num=11, endpoint=True)
y = np.cos(-x**2/9.0)
xnew = np.linspace(0, 10, num=41, endpoint=True)

# Define interpolators.
f_linear = interp1d(x, y)
f_cubic = interp1d(x, y, kind='cubic')

# Plot.
plt.plot(x, y, 'o', label='data')
plt.plot(xnew, f_linear(xnew), '-', label='linear')
plt.plot(xnew, f_cubic(xnew), '--', label='cubic')
plt.legend(loc='best')
plt.show()

在这里输入图片描述

稍微修改过以提高可读性。

69

在这个例子中,样条曲线效果不错,但如果你的函数本身不够平滑,而你又想让它看起来更平滑,可以试试下面的方法:

from scipy.ndimage.filters import gaussian_filter1d

ysmoothed = gaussian_filter1d(y, sigma=2)
plt.plot(x, ysmoothed)
plt.show()

如果你增加sigma的值,就能得到一个更平滑的函数。

不过要小心使用这个方法。它会改变原来的数值,可能不是你想要的效果。

225

你可以使用 scipy.interpolate.spline 来自己平滑处理数据:

from scipy.interpolate import spline

# 300 represents number of points to make between T.min and T.max
xnew = np.linspace(T.min(), T.max(), 300)  

power_smooth = spline(T, power, xnew)

plt.plot(xnew,power_smooth)
plt.show()

不过,从 scipy 0.19.0 开始,spline 已经不再推荐使用了,建议改用 BSpline 类。

spline 切换到 BSpline 不是简单的复制粘贴,需要稍微调整一下:

from scipy.interpolate import make_interp_spline, BSpline

# 300 represents number of points to make between T.min and T.max
xnew = np.linspace(T.min(), T.max(), 300) 

spl = make_interp_spline(T, power, k=3)  # type: BSpline
power_smooth = spl(xnew)

plt.plot(xnew, power_smooth)
plt.show()

之前的效果: screenshot 1

之后的效果: screenshot 2

撰写回答