一、二維的插值方法:
- 原始數據(x,y)
- 先對橫坐標x進行擴充數據量,采用linspace。【如下面例子,由7個值擴充到300個】
- 采用scipy.interpolate中的spline來對縱坐標數據y進行插值【也由7個擴充到300個】。
- 畫圖
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])
#插值 from scipy.interpolate import spline xnew = np.linspace(T.min(),T.max(),300) #300 represents number of points to make between T.min and T.max power_smooth = spline(T,power,xnew) print(xnew.shape) #(300,) print(power_smooth.shape) #(300,)
#畫圖 plt.plot(xnew,power_smooth) plt.show()
二、三維平滑圖---插值:
1、數據:
x = [0.1,0.2,……,0.9] (shape = (9))
y = [0.1,0.2,……,0.9] (shape = (9))
z = 【81個數據】(shape = (81))
生成數據:

x = np.linspace(0.1,0.9,9) y = np.linspace(0.1,0.9,9) z = np.random.rand(81)
2、將x和y進行擴充到想要的大小:
【兩種方法:np.arange和np.linspace】
xnew = np.arange(0.1, 1, 0.03) 【shape=(31)】
ynew = np.arange(0.1, 1, 0.03) 【shape=(31)】
或者
xnew = np.linspace(0.1, 0.9, 31)
ynew = np.linspace(0.1, 0.9, 31)
3、對z進行插值:
采用 scipy.interpolate.interp2d函數進行插值。
x,y原數據:【x.shape=9,y.shape=9,z.shape=81】
f = interpolate.interp2d(x, y, z, kind='cubic')
x,y擴充數據:【xnew.shape=31,y.shape=31】
znew = f(xnew, ynew) 【得到的znew.shape = (31,31)】
znew為插值后的z
4、畫圖:
采用 from mpl_toolkits.mplot3d import Axes3D進行畫三維圖
Axes3D簡單用法:

import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() ax = fig.add_subplot(111, projection='3d')
比如采用plot_trisurf畫三維圖:plot_trisurf(x,y,z)
【plot_trisurf對數據要求是:x.shape = y.shape = z.shape,所以x和y的shape需要修改,采用np.meshgrid,且都為一維數據】

#修改x,y,z輸入畫圖函數前的shape xx1, yy1 = np.meshgrid(xnew, ynew) newshape = (xx1.shape[0])*(xx1.shape[0]) y_input = xx1.reshape(newshape) x_input = yy1.reshape(newshape) z_input = znew.reshape(newshape)
5、所有代碼:
# 載入模塊 import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm import pandas as pd import seaborn as sns from scipy import interpolate #生成數據 x = np.linspace(0.1,0.9,9) y = np.linspace(0.1,0.9,9) z = np.random.rand(81) #插值 # xx, yy = np.meshgrid(x, y) f = interpolate.interp2d(x, y, z, kind='cubic') xnew = np.arange(0.1, 1, 0.03) ynew = np.arange(0.1, 1, 0.03) znew = f(xnew, ynew) #修改x,y,z輸入畫圖函數前的shape xx1, yy1 = np.meshgrid(xnew, ynew) newshape = (xx1.shape[0])*(xx1.shape[0]) y_input = xx1.reshape(newshape) x_input = yy1.reshape(newshape) z_input = znew.reshape(newshape) #畫圖 sns.set(style='white') fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.plot_trisurf(x_input,y_input,z_input,cmap=cm.coolwarm) plt.show()