【问题标题】:Interpolating a curve on a plot在绘图上插值曲线
【发布时间】:2022-08-09 16:40:15
【问题描述】:

我希望在给定多个点(1-d x 和 y 数组)的情况下绘制一条平滑曲线。 我以为我可以使用包make_interp_spline,但看起来x 数组需要均匀排序...如何使用make_interp_spline 而不对数组的x 维度进行排序或解决错误?

from scipy.interpolate import make_interp_spline
import numpy as np
#from scipy import stats
import matplotlib.pyplot as plt


x = np.array([-31,-30,-30,-32,-36,-39])
y = np.array([60,62,64,65,64,64])

#plot non-interpolated curve 
plt.plot(x,y);

#x = x.reshape(6)
#y = y.reshape(6)

# wher the error occurs about the 1d sorted array
X_Y_Spline = make_interp_spline(x, y)

X_ = np.linspace(x.min(), x.max(), 500)
Y_ = X_Y_Spline(X_)

plt.plot(X_, Y_);


---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/tmp/ipykernel_2083810/662623888.py in <module>
      7 #y = y.reshape(6)
      8 
----> 9 X_Y_Spline = make_interp_spline(x, y)
     10 
     11 X_ = np.linspace(x.min(), x.max(), 500)

~/miniconda3/envs/py3_std_maps/lib/python3.9/site-packages/scipy/interpolate/_bsplines.py in make_interp_spline(x, y, k, t, bc_type, axis, check_finite)
    784 
    785     if x.ndim != 1 or np.any(x[1:] < x[:-1]):
--> 786         raise ValueError(\"Expect x to be a 1-D sorted array_like.\")
    787     if np.any(x[1:] == x[:-1]):
    788         raise ValueError(\"Expect x to not have duplicates\")

ValueError: Expect x to be a 1-D sorted array_like.

    标签: python scipy jupyter interpolation


    【解决方案1】:

    最好使用“scipy.interpolate”中的“interp1d”。

    from scipy.interpolate import interp1d
    import numpy as np
    import matplotlib.pyplot as plt
    
    
    x = np.array([-31,-30,-30,-32,-36,-39])
    y = np.array([60,62,64,65,64,64])
    
    
    X_Y_Spline = interp1d(x, y)
    X_ = np.linspace(x.min(), x.max(), 500)
    Y_ = X_Y_Spline(X_)
    
    plt.plot(X_, Y_)
    
    

    【讨论】:

      猜你喜欢
      • 2019-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-19
      • 1970-01-01
      • 2019-11-20
      • 1970-01-01
      相关资源
      最近更新 更多