1. 程式人生 > >Python畫三維圖-----插值平滑資料

Python畫三維圖-----插值平滑資料

一、二維的插值方法:

  1. 原始資料(x,y)
  2. 先對橫座標x進行擴充資料量,採用linspace。【如下面例子,由7個值擴充到300個】
  3. 採用scipy.interpolate中的spline來對縱座標資料y進行插值【也由7個擴充到300個】。
  4. 畫圖
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)
View Code

 

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')
View Code

比如採用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)
View Code

 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()