[英]Smoothening a lineplot: Fix TypeError for interpolator1D y_axis
我正在尝试使用 scipy.interpolate 平滑线图。 但是,由于某种原因,我在使用此方法时出现错误。
这是我的代码:
import numpy as np
from scipy import interpolate
import matplotlib.pyplot as plt
x = np.array([1348.4256 , 1342.99776, 1345.86432, 1352.97024, 1353.09312, 1355.0304])
y = np.array([232.2108 , 233.60184, 236.09988, 235.40544, 235.51776, 238.42728])
smooth = interpolate.interp1d(x, y, 'cubic')
y_range = np.linspace(min(y), max(y), 20)
plt.plot(smooth(y_range), y_range)
plt.plot(x, y,
linewidth=1)
plt.plot(smooth(y_range),
y_range)
plt.show()
我得到的错误是TypeError: descriptor '_y_axis' for '_Interpolator1D' objects doesn't apply to 'interp1d' object
我的问题是:我该怎么做才能解决此错误并在这条线上获得平滑的绘图?
您的smooth()
函数在min(x)
到max(x)
的范围内工作正常,并为此类操作返回y
值。 当您提供任何超出限制的值时,您将收到错误消息。
如果要通过指定y
值来为x
进行插值,请尝试以下代码:
smooth_for_y = interpolate.interp1d(y, x, 'cubic')
y_range = np.linspace(min(y), max(y), 20)
插值:
smooth_for_y( y_range )
输出:
array([1348.4256 , 1344.64896129, 1342.64269324, 1342.09678777,
1342.70123678, 1344.14603221, 1346.12116596, 1348.31662995,
1350.4224161 , 1352.12851632, 1353.09777093, 1350.92268063,
1345.07380415, 1337.3796737 , 1329.67182218, 1323.78178249,
1321.54108752, 1324.78127019, 1335.33386338, 1355.0304 ])
这是基于一些假设的可能解决方案(在代码中提到)。
import numpy as np
from scipy import interpolate
import matplotlib.pyplot as plt
# raw data
x = np.array([1348.4256 , 1342.99776, 1345.86432, 1352.97024, 1353.09312, 1355.0304])
y = np.array([232.2108 , 233.60184, 236.09988, 235.40544, 235.51776, 238.42728])
smooth_for_y = interpolate.interp1d(x, y, 'cubic')
x_range = np.linspace(min(x), max(x), 20, endpoint=True)
y_smoothed = smooth_for_y( x_range )
# plot data as red dots
plt.scatter(x, y, linewidth=1, color="red")
# plot smoothed line across data
# assuming first point begins at xmin, ends at xmax, thus ...
# ignoring the sequence of the original data
plt.plot(x_range, y_smoothed)
plt.show()
剧情:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.