本文介绍了使用 PyPlot 绘制平滑线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下绘制图形的简单脚本:

将 matplotlib.pyplot 导入为 plt将 numpy 导入为 npT = np.array([6, 7, 8, 9, 10, 11, 12])功率 = 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 中是否有一种简单的方法可以做到这一点?我找到了一些教程,但它们看起来都很复杂.

解决方案

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

from scipy.interpolate 导入样条# 300 表示 T.min 和 T.max 之间的点数xnew = np.linspace(T.min(), T.max(), 300)power_smooth = spline(T, power, xnew)plt.plot(xnew,power_smooth)plt.show()

spline 在 scipy 0.19.0 中已弃用,请改用 BSpline 类.

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

from scipy.interpolate import make_interp_spline, BSpline# 300 表示 T.min 和 T.max 之间的点数xnew = np.linspace(T.min(), T.max(), 300)spl = make_interp_spline(T, power, k=3) # 类型:BSplinepower_smooth = spl(xnew)plt.plot(xnew,power_smooth)plt.show()

之前:

之后:

I've got the following simple script that plots a graph:

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()

As it is now, the line goes straight from point to point which looks ok, but could be better in my opinion. What I want is to smooth the line between the points. In Gnuplot I would have plotted with smooth cplines.

Is there an easy way to do this in PyPlot? I've found some tutorials, but they all seem rather complex.

解决方案

You could use scipy.interpolate.spline to smooth out your data yourself:

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()


Switching from spline to BSpline isn't a straightforward copy/paste and requires a little tweaking:

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()


Before:

After:

这篇关于使用 PyPlot 绘制平滑线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-16 20:19