简体   繁体   English

使用SciPy插值数据

[英]Interpolating Data Using SciPy

I have two arrays of data that correspond to x and y values, that I would like to interpolate with a cubic spline. 我有两个分别对应于x和y值的数据数组,我想用三次样条插值。

I have tried to do this, but my interpolated function doesn't pass through my data points. 我试图这样做,但是我的插值函数没有通过我的数据点。

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

    re = np.array([0.2,2,20,200,2000,20000],dtype = float)
    cd = np.array([103,13.0,2.72,0.800,0.401,0.433],dtype = float)

    plt.yscale('log')
    plt.xscale('log')
    plt.xlabel( "Reynold's number" )
    plt.ylabel( "Drag coefficient" )
    plt.plot(re,cd,'x', label='Data')

    x = np.linspace(0.2,20000,200000)
    f = interp1d(re,cd,kind='cubic')
    plt.plot(x,f(x))

    plt.legend()

    plt.show()

What I end up with looks like this; 我最终看到的是这样的;

在此处输入图片说明

Which is clearly an awful representation of my function. 这显然是我功能的糟糕表现。 What am I missing here? 我在这里想念什么?

Thank you. 谢谢。

You can get the result you probably expect (smooth spline on the log axes) by doing this: 通过执行以下操作,您可以获得预期的结果(对数轴上的平滑样条):

f = interp1d(np.log(re),np.log(cd), kind='cubic')
plt.plot(x,np.exp(f(np.log(x))))

This will build the interpolation in the log space and plot it correctly. 这将在日志空间中构建插值并正确绘制它。 Plot your data on a linear scale to see how the cubic has to flip to get the tail on the left hand side. 以线性比例绘制数据,以查看三次方必须如何翻转才能使尾部位于左侧。

The main thing you are missing is the log scaling on your axes. 您缺少的主要内容是轴上的对log缩放。 The spline shown is not an unreasonable result given your input data. 对于您输入的数据,显示的样条曲线并不是不合理的结果。 Try drawing the plot with plt.xscale('linear') instead of plt.xscale('log') . 尝试使用plt.xscale('linear')而不是plt.xscale('log')绘制图。 Perhaps a cubic spline is not the best interpolation technique, at least on the raw data. 至少在原始数据上,三次样条也许不是最佳插值技术。 A better option may be to interpolate on the log of the data insead. 更好的选择可能是在数据导入日志中进行插值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM