# -*- coding: utf-8 -*-
"""
示範二維插值。
"""
# -*- coding: utf-8 -*-
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib as mpl
from scipy import interpolate
import matplotlib.cm as cm
import matplotlib.pyplot as plt
def func(x, y):
return (x + y) * np.exp(-5.0 * (x ** 2 + y ** 2))
# X-Y軸分為20*20的網格
x = np.linspace(-1, 1, 20)
y = np.linspace(-1, 1, 20)
x, y = np.meshgrid(x, y) # 20*20的網格資料
fvals = func(x, y) # 計算每個網格點上的函數值 15*15的值
fig = plt.figure(figsize=(9, 6)) #設定圖的大小
# Draw sub-graph1
ax = plt.subplot(1, 2, 1, projection='3d') #設定圖的位置
surf = ax.plot_surface(x, y, fvals, rstride=2, cstride=2, cmap=cm.coolwarm, linewidth=0.5, antialiased=True) #第四個第五個參數表示隔多少個取樣點畫一個小面,第六個表示畫圖類型,第七個是畫圖的線寬,第八個表示抗鋸齒
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('f(x, y)') #标簽
plt.colorbar(surf, shrink=0.5, aspect=5) # 标注
# 二維插值
newfunc = interpolate.interp2d(x, y, fvals, kind='cubic') # newfunc為一個函數
# 計算100*100的網格上的插值
xnew = np.linspace(-1, 1, 100) # x
ynew = np.linspace(-1, 1, 100) # y
fnew = newfunc(xnew, ynew) # 僅僅是y值 100*100的值 np.shape(fnew) is 100*100
xnew, ynew = np.meshgrid(xnew, ynew)
ax2 = plt.subplot(1, 2, 2, projection='3d')
surf2 = ax2.plot_surface(xnew, ynew, fnew, rstride=2, cstride=2, cmap=cm.coolwarm, linewidth=0.5, antialiased=True)
ax2.set_xlabel('xnew')
ax2.set_ylabel('ynew')
ax2.set_zlabel('fnew(x, y)')
plt.colorbar(surf2, shrink=0.5, aspect=5) # 标注
plt.show()