Python3D繪圖Axes3D-surfaceplot

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter

fig = plt.figure(figsize=(16,12))
ax = fig.gca(projection="3d")

#準備數據
x = np.arange(-5, 5, 0.25)   #生成[-5,5] 間隔0.25的數列,間隔越小,曲面越平滑
y = np.arange(-5, 5, 0.25)
x, y = np.meshgrid(x,y)   #格點矩陣,原來的x行向量向下複製len(y)此形成
# len(y)*len(x)的矩陣,即爲新的x矩陣;原來的y列向量向右複製len(x)次,形成
# len(y)*len(x)的矩陣,即爲新的y矩陣;新的x矩陣和新的y矩陣shape相同
r = np.sqrt(x ** 2 + y ** 2)
z = np.sin(r)

surf = ax.plot_surface(x, y, z, cmap=cm.coolwarm)   #cmap指color map

#自定義z軸
ax.set_zlim(-1, 1)
ax.zaxis.set_major_locator(LinearLocator(20))   #z軸網格線的疏密,刻度的疏密,20表示刻度的個數
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))   #將z的value子符串轉爲float,保留2位小數

#設置座標軸的label和標題
ax.set_xlabel('x', size=15)
ax.set_ylabel('y', size=15)
ax.set_zlabel('z', size=15)
ax.set_title("Surface plot", weight='bold', size=20)

#添加右側的色卡條
fig.colorbar(surf, shrink=0.6, aspect=8) #shrink表示整體收縮比例,aspect僅對bar的寬度有影響,
# aspect值越大,bar越窄

plt.show()

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章