scipy 在图上插入曲线

js5cn81o  于 2022-11-10  发布在  其他
关注(0)|答案(3)|浏览(192)

我希望绘制一条平滑的曲线,给出一些点(一维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.
8i9zcol2

8i9zcol21#

最好使用“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_)
h9vpoimq

h9vpoimq2#

解决方法是在xy数组之后建立单调递增的n维度。
请参阅:

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

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

x_spline = interp1d(n, x,kind='cubic')

n_ = np.linspace(n.min(), n.max(), 500)
y_spline = interp1d(n, y,kind='cubic')

x_ = x_spline(n_)
y_ = y_spline(n_)

plt.plot(x_, y_)

plt.plot(x,y);

zdwk9cvp

zdwk9cvp3#

只需对x数组进行np.argsort,并使用结果同时对x和y进行排序。

相关问题